I have the following C
code :
int *a;
size_t size = 2000*sizeof(int);
a = (int *) 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 = (char *) malloc(size);
I think a 2 step approach is best, because c 2-d arrays are just and array of arrays. The first step is to allocate a single array, then loop through it allocating arrays for each column as you go. This article gives good detail.
malloc does not allocate on specific boundaries, so it must be assumed that it allocates on a byte boundary.
The returned pointer can then not be used if converted to any other type, since accessing that pointer will probably produce a memory access violation by the CPU, and the application will be immediately shut down.