See for instance How do I allocate a 2 D array with contigious memory ? How Do I use it to access rows and columns? Give me an example
If the thing that is to be avoided is the multiple calls to malloc()
, then here is an alternative way to allocate a 2D array:
int row=42;
int col=35;
int** array=malloc(row*sizeof(int*));
if(array==NULL){fprintf(stderr,"malloc failed\n");exit(1);}
array[0]=malloc(row*col*sizeof(int));
if(array[0]==NULL){fprintf(stderr,"malloc failed\n");exit(1);}
int i;
for(i=1;i<row;i++){
array[i]=&array[0][i*col];
}
...
free(array[0]);
free(array);
Values can still be retreived by int val=array[i][j]
and set by array[i][j]=42;
Compared to the method that is introduced in your question, the present method ensures that the rows are contiguous in memory. Hence, such array of float
or double
can easily be used by the LAPACK library as a matrix, of by the FFTW library to compute the 2D Fast Fourier Transform of an image (convolution...). But increasing the size of the array on the fly is much harder.
Notice that the size of the array can be computed by the program at execution time, days after the program is compiled.
This trick can be extended to higher dimensions (3D, 4D,...) but it does not become more beautiful !