I have seen dozens of questions about “what’s wrong with my code” regarding multidimensional arrays in C. For some reason people can’t seem to wrap their head around what is
There are at least four different ways to create or simulate a multi-dimensional array in C89.
One is "allocate each row separately", described by Mike in his answer. It is not a multidimensional array, it merely imitates one (in particular it mimics the syntax for accessing an element). It can be useful in the case where each row has different size, so you aren't representing a matrix but rather something with a "ragged edge".
One is "allocate a multidimensional array". It looks likes this:
int (*rows)[NUM_ROWS][NUM_COLS] = malloc(sizeof *rows);
...
free(rows);
Then the syntax to access element [i,j] is (*rows)[i][j]
. In C89, both NUM_COLS
and NUM_ROWS
must be known at compile-time. This is a true 2-D array, and rows
is a pointer to it.
One is, "allocate an array of rows". It looks like this:
int (*rows)[NUM_COLS] = malloc(sizeof(*rows) * NUM_ROWS);
...
free(rows);
Then the syntax to access element [i,j] is rows[i][j]
. In C89, NUM_COLS
must be known at compile-time. This is a true 2-D array.
One is, "allocate a 1-d array and pretend". It looks like this:
int *matrix = malloc(sizeof(int) * NUM_COLS * NUM_ROWS);
...
free(matrix);
Then the syntax to access element [i,j] is matrix[NUM_COLS * i + j]
. This (of course) is not a true 2-D array. In practice it has the same layout as one.