I l@ve RuBoard Previous Section Next Section

5.5 Multidimensional Arrays

Arrays can have more than one dimension. The declaration for a two-dimensional array is:

type variable[size1][size2]; // comment

For example:

// a typical matrix
int matrix[2][4]; 

Notice that C++ does not follow the notation used in other languages of matrix[10,12].

To access an element of the matrix we use the following notation:

matrix[1][2] = 10; 

C++ allows you to use as many dimensions as needed (limited only by the amount of memory available). Additional dimensions can be tacked on:

four_dimensions[10][12][9][5]; 

Initializing multidimensional arrays is similar to initializing single-dimension arrays. A set of curly braces { } encloses each element. The declaration:

// a typical matrix
int matrix[2][4]; 

can be thought of as a declaration of an array of dimension 2 whose elements are arrays of dimension 4. This array is initialized as follows:

// a typical matrix
int matrix[2][4] = 
    { 
        {1, 2, 3, 4}, 
        {10, 20, 30, 40} 
    };

This is shorthand for:

matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 4;

matrix[1][0] = 10;
matrix[1][1] = 20;
matrix[1][2] = 30;
matrix[1][3] = 40;

Question 5-2: Why does the program in Example 5-9 print incorrect answers?

Example 5-9. array/array.cpp
#include <iostream>

int array[3][5] = {     // Two dimensional array
   { 0,  1,  2,  3,  4 },
   {10, 11, 12, 13, 14 },
   {20, 21, 22, 23, 24 }
};

int main(  )
{
    std::cout << "Last element is " << array[2,4] << '\n';
    return (0);
}

When run on a Sun 3/50 this program generates:

Last element is 0x201e8

Your answers may vary.

You should be able to spot the error because one of the statements looks like it has a syntax error in it. It doesn't, however, and the program compiles because we are using a new operator that has not yet been introduced. But even though you don't know about this operator, you should be able to spot something funny in this program.

    I l@ve RuBoard Previous Section Next Section