How do we allocate a 2-D array using One malloc statement

Just compute the total amount of memory needed for both nrows row-pointers, and the actual data, add it all up, and do a single call:

int **array = malloc(nrows * sizeof *array + (nrows * (ncolumns * sizeof **array));

If you think this looks too complex, you can split it up and make it a bit self-documenting by naming the different terms of the size expression:

int **array; /* Declare this first so we can use it with sizeof. */
const size_t row_pointers_bytes = nrows * sizeof *array;
const size_t row_elements_bytes = ncolumns * sizeof **array;
array = malloc(row_pointers_bytes + nrows * row_elements_bytes);

You then need to go through and initialize the row pointers so that each row’s pointer points at the first element for that particular row:

size_t i;
int * const data = array + nrows;
for(i = 0; i < nrows; i++)
  array[i] = data + i * ncolumns;

Note that the resulting structure is subtly different from what you get if you do e.g. int array[nrows][ncolumns], because we have explicit row pointers, meaning that for an array allocated like this, there’s no real requirement that all rows have the same number of columns.

It also means that an access like array[2][3] does something distinct from a similar-looking access into an actual 2d array. In this case, the innermost access happens first, and array[2] reads out a pointer from the 3rd element in array. That pointer is then treatet as the base of a (column) array, into which we index to get the fourth element.

In contrast, for something like

int array2[4][3];

which is a “packed” proper 2d array taking up just 12 integers’ worth of space, an access like array[3][2] simply breaks down to adding an offset to the base address to get at the element.

Leave a Comment