Multi-Dimensional Arrays in C: are they jagged? Multi-Dimensional Arrays in C: are they jagged? arrays arrays

Multi-Dimensional Arrays in C: are they jagged?


A multidimensional array in C is contiguous. The following:

int m[4][5];

consists of 4 int[5]s laid out next to each other in memory.

An array of pointers:

int *m[4];

is jagged. Each pointer can point to (the first element of) a separate array of a different length.

m[i][j] is equivalent to *(*(m+i)+j). See the C11 standard, section 6.5.2.1:

The deļ¬nition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))

Thus, m[i][j] is equivalent to (*(m+i))[j], which is equivalent to *(*(m+i)+j).

This equivalence exists because in most contexts, expressions of array type decay to pointers to their first element (C11 standard, 6.3.2.1). m[i][j] is interpreted as the following:

  • m is an array of arrays, so it decays to a pointer to m[0], the first subarray.
  • m+i is a pointer to the ith subarray of m.
  • m[i] is equivalent to *(m+i), dereferencing a pointer to the ith subarray of m. Since this is an expression of array type, it decays to a pointer to m[i][0].
  • m[i][j] is equivalent to *(*(m+i)+j), dereferencing a pointer to the jth element of the ith subarray of m.

Note that pointers to arrays are different from pointers to their first element. m+i is a pointer to an array; it is not an expression of array type, and it does not decay, whether to a pointer to a pointer or to any other type.


A consecutive memory area:

int arr[N][M];

A non-consecutive memory area:

int** arr = malloc(N*sizeof(int*));for (int i=0; i<N; i++)    arr[i] = malloc(M*sizeof(int));

You can use arr as a 2-dimensional array (e.g., arr[1][2] = 3) in both cases. But you can safely apply larger copy operations, such as memset(arr,0,N*M*sizeof(int)), only in the first case.


This would depend.

Multidimensional arrays in C are sequentially arranged.

You can create jagged arrays if you want using pointers.