Page 98 - Programming Microcontrollers in C
P. 98
Multidimensional Arrays 83
array must always be understood as being arrays of arrays of arrays
and so forth. For example, the declaration
int ar[3][5];
defines three arrays of five elements each. We have already seen that
data stored in this array is column major. The second argument points
to a column in the two-dimensional array, and ar[n][0] and
ar[n][1] are stored in adjacent memory locations. Following the
logic of array names and pointers, the array name ar is a pointer to
the first element in the array. The value obtained when using ar as
an rvalue is &ar[0][0]. The order of evaluation of the square
brackets is from left to right so that *(ar+1) is a pointer to the
element ar[1][0] in the array. Think of the two-dimensional ar
ray as being *(ar+n)[i] where n has a range from 0 to 2 and i
has a range from 0 to 4. An increment in n here will increment the
absolute value of the pointer by 5*sizeof(int).
These ideas can be carried to the next level. The element *(ar+n)
is a pointer to the first element of a five-element array. Therefore, the
evaluation of *(*(ar+n)+i) is the value found in the location
ar[n][i]. The important item is that the right-most argument in
multiple dimensional arrays point to adjacent memory locations, and
the increments of the left arguments step the corresponding pointer
value from array to array to array.
These ideas can be extended to arrays of more than two dimen
sions. Had the array been
double br[3][4][5];
then *(*(*(br+1)+2)+3) would be the element br[1][2][3]
from the above array, and *(*(br+1)+2)+3 is a pointer to this
element.
EXERCISES
1. Write a function that will receive the year and the Julian date of
that year, and calculate the month and date.
2. Write a function that will calculate the product of a 4 by 4 matrix
and a scalar. The scalar product requires multiplication of each
element in the matrix by the scalar value.