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);
2-D Array Dynamic Memory Allocation
The other approach would be to allocate one contiguous chunk of memory comprising header block for pointers to rows as well as body block to store actual data in rows. Then just mark up memory by assigning addresses of memory in body to the pointers in header on per-row basis. It would look like follows:
The advantage of this approach is elegant freeing of memory and ability to use array-like notation to access elements of the resulting 2D array.
If every element in b has different lengths, then you need to do something like:
Equivalent memory allocation for
char a[10][20]
would be as follows.I hope this looks simple to understand.
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.The typical form for dynamically allocating an NxM array of type T is
If each element of the array has a different length, then replace M with the appropriate length for that element; for example