Jan 16, 2002
Reading assignment:
Deitel and Deitel Chapter 4.9
-or Wang section 4.3
Multi-dimensional arrays:
- In c++ you can store a two-dimensional block of variables, like a matrix,
in what's called a two-dimensional array, or double-subscripted array
- Define it, for example, like this:
int matrix_variable[2][5];
This defines a 2 by 5 array of integers with the name matrix_variable
Think of the first index as the rows, the second as the columns
The picture in your mind should look like this:
2 82 6 1 17
1 -2 8 16 -1
- To access individual elements, put a subscript in for the rows and
for the columns, for example, val = matrix_variable[1][3];
Both dimensions are indexed starting at 0, so val would be equal
to 16 for the above array.
It shouldn't surprise you that these individual elements are lvalues
since that's how it works for 1-dimensional arrays
- Warning: Don't accidentally write matrix_variable[1, 3] instead of
matrix_variable[1][3]
- There's special syntax for initializing, for example
int another_array[3][2] = { {1, 2}, {3, 4}, {5, 6}};
This definition initializes the array as
1 2
3 4
5 6
- When you pass a 2-D array to a function, you must specify the number
of columns in the parameter list in both the function prototype
and the function definition, for example:
void example_function(int [][5]); // prototype
void example_function(int array[][5]){ //function definition
function body
}
- If you give a double-subscripted array just one subsript, as in
matrix_variable[7], the compiler will not complain - it counts out
to the 7th element in the array by counting along the 1st row, then
the 2nd, and so forth. For the values defined in matrix_variable above,
matrix_variable[7] would have the value 8
- There's a good example program for double-subsripted arrays in
D&D page 277-278
- You will need a double-subscripted array for your next programming
assignment
- Know that you can have arrays of higher dimensions as well
Here's the simple double-subsripted array program we did in class:
doublearr.cpp