I have the following C code :
int *a;
size_t size = 2000*sizeof(int);
a = malloc(size);
which works fine. But if I have the following :
char **b = malloc(2000*sizeof *b);
where every element of b has different length.
How is it possible to do the same thing for b as i did for a; i.e. the following code would hold correct?
char *c;
size_t size = 2000*sizeof(char *);
c = malloc(size);
First, you need to allocate array of pointers like
char **c = malloc( N * sizeof( char* )), then allocate each row with a separate call tomalloc, probably in the loop:If you know the total number of elements (e.g.
N*M) you can do this in a single allocation.