Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using malloc for allocation of multi-dimensional arrays with different row lengths

Tags:

arrays

c

malloc

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); 
like image 544
asel Avatar asked Dec 28 '09 17:12

asel


1 Answers

First, you need to allocate array of pointers like char **c = malloc( N * sizeof( char* )), then allocate each row with a separate call to malloc, probably in the loop:

 /* N is the number of rows  */ /* note: c is char** */ if (( c = malloc( N*sizeof( char* ))) == NULL ) { /* error */ }  for ( i = 0; i < N; i++ ) {   /* x_i here is the size of given row, no need to    * multiply by sizeof( char ), it's always 1    */   if (( c[i] = malloc( x_i )) == NULL )   { /* error */ }    /* probably init the row here */ }  /* access matrix elements: c[i] give you a pointer  * to the row array, c[i][j] indexes an element  */ c[i][j] = 'a'; 

If you know the total number of elements (e.g. N*M) you can do this in a single allocation.

like image 84
Nikolai Fetissov Avatar answered Oct 08 '22 06:10

Nikolai Fetissov