Accessing elements of multi-dimensional arrays of various dimensions
To access an array element using array notation, we must be consistent in using both the dimensions of the array and a valid range of offsets for each dimension.
To access an element of an array, we would use the [
and ]
notation for each of its offsets in each dimension. Remember that C indices are zero-based. It is better to think of them as offsets from the array base—for example, the column offset for the first element in a 1D array is [0]
; the row offset for the first row of a 2D array is [0][x]
; the layer offset for the first layer of a 3D array is [0][y][x]
. Putting this knowledge to work, let's access the third element of our various arrays, as follows:
int third;
first = array1D[2]; // third element.
first = array2D[0][2]; // third element of 1st row.
first = array3D[0][0][2]; // third element of 1st layer and
...