<< Chapter < Page | Chapter >> Page > |
A multidimensional array in C is merely an array whose elements are themselves arrays. The elements of an n-dimensional array are (n-1)-dimensional arrays. For example, each element of a two-dimensional array is a one-dimensional array. The elements of a one-dimensional array, of course, do not have an array type.
A multidimensional array declaration has a pair of brackets for each dimension:
char screen[10][40][80]; // A three-dimensional array.
The array screen consists of the 10 elements screen[0] to screen[9]. Each of these elements is a two-dimensional array, consisting in turn of 40 one-dimensional arrays of 80 characters each. All in all, the array screen contains 32,000 elements with the type char.
Two-dimensional arrays are also called matrices. Because they are so frequently used, they merit a closer look. It is often helpful to think of the elements of a matrix as being arranged in rows and columns. Thus the matrix mat in the following definition has three rows and five columns:
float mat[3][5];
The three elements mat[0], mat[1], and mat[2] are the rows of the matrix mat. Each of these rows is an array of five float elements. Thus the matrix contains a total of 3 x 5 = 15 float elements, as the following diagram illustrates:
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
mat[0] | 0.0 | 0.1 | 0.2 | 0.3 | 0.4 |
mat[1] | 1.0 | 1.1 | 1.2 | 1.3 | 1.4 |
mat[2] | 2.0 | 2.1 | 2.2 | 2.3 | 2.4 |
The subscript operator [ ] provides an easy way to address the individual elements of an array by index. If myArray is the name of an one dimensional array and i is an integer, then the expression myArray[i]designates the array element with the index i. Array elements are indexed beginning with 0. Thus, if len is the number of elements in an array, the last element of the array has the index len-1.
The following code fragment defines the array myArray and assigns a value to each element.
#define A_SIZE 4
long myarray[A_SIZE];
for (int i = 0; i<A_SIZE; ++i)
myarray[i]= 2 * i;
The diagram in [link] illustrates the result of this assignment loop.
To access a char element in the three-dimensional array screen, you must specify three indices. For example, the following statement writes the character Z in a char element of the array:
screen[9][39][79] = 'Z';
If you do not explicitly initialize an array variable, the usual rules apply: if the array has automatic storage duration, then its elements have undefined values. Otherwise, all elements are initialized by default to the value 0.
int a[ ] = { 1, 2, 4, 8 }; // An array with four elements.
int a[4] = {1, 2};int a[ ] = {1, 2, 0, 0};int a[ ] = {1, 2, 0, 0, };int a[4] = {1, 2, 0, 0, 5};
Notification Switch
Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?