Skip to content

Instantly share code, notes, and snippets.

@mvasilkov
Created February 14, 2012 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvasilkov/1827615 to your computer and use it in GitHub Desktop.
Save mvasilkov/1827615 to your computer and use it in GitHub Desktop.
Single-malloc char** allocation.
#include <stdio.h>
#include <stdlib.h>
#define N (3)
const size_t offset = sizeof(char *) * N,
length = (sizeof(char *) + sizeof(char) * N) * N;
int main(int argc, char **argv) {
char **foo = (char **)malloc(length);
int i, j;
for (i = 0; i < N; ++i) {
foo[i] = (char *)(foo + offset + i * N);
}
/* usage */
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
foo[i][j] = 'a' + i * j;
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j)
printf(" %c", foo[i][j]);
putchar('\n');
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment