Multi-Dimensional Arrays in C: are they jagged?

ansi-c, arrays, c, jagged-arrays, multidimensional-array

Solution

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 definition 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 `i`th subarray of `m`.

- `m[i]` is equivalent to `*(m+i)`, dereferencing a pointer to the `i`th 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 `j`th element of the `i`th 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.

Problem

A simple question about the C programming language (ANSI-C): Are the multi-dimensional arrays in C jagged? I mean - are we talking about "array of arrays" (one array of pointers to other addresses in the memory) , or this is just "long one-dimensional array" (which is stored sequentially in the memory)? What that bothers me is that I'm kinda sure that: `matrix[i][j]` is equivalent to `* ( * (matrix + i) + j)`

Original source

Related problems