I have problem to correctly interpret two different ways of dynamically allocation 2D arrays in C.
This first method reads (for readability, I left out the if(arr==NULL)
checks):
double** matrix_d( long int Nrows, long int Ncols ) {
long int ii;
double** arr;
// allocate pointer to rows
arr = calloc( Nrows , (sizeof *arr));
for( ii=0 ; ii < Nrows; ii++) {
// allocate pointer to each column (?)
arr[ii] = calloc( Ncols , (sizeof **arr) );
}
return arr;
}
The second method reads (again, omitting the check of the return-value of calloc):
double** matrix_d2( long int Nrows, long int Ncols ) {
long int ii;
double** arr;
// allocate pointers to rows
arr = calloc( Nrows , (sizeof *arr) );
// allocate rows (?)
arr[0] = calloc( Nrows*Ncols, (sizeof arr) );
// set pointers to rows (?)
for( ii=0 ; ii < Nrows; ii++)
arr[ii] = (*arr + Ncols*ii);
return arr;
The comment-lines reveal probably my lack of understanding the memory allocation properly... especially the second method is somehow confusing to me (but seems to be "better" in that sense that it requires only 2 calloc/malloc calls).
Could one of you probably point me to the correct interpretation? That would be greatly appreciated! }
EDIT: there was a typo in both methods' first calloc call