Multidimensional arrays in C++

Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type.



jimmy represents a bidimensional array of 3 per 5 elements of type int. The way to declare this array in C++ would be:
int jimmy [3][5];

and, for example, the way to reference the second element vertically and fourth horizontally in an expression would be:
jimmy[1][3]



(remember that array indices always begin by zero).

Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many indices as needed. But be careful! The amount of memory needed for an array rapidly increases with each dimension. For example:

char century [100][365][24][60][60];

declares an array with a char element for each second in a century, that is more than 3 billion chars. So this declaration would consume more than 3 gigabytes of memory!

Multidimensional arrays are just an abstraction for programmers, since we can obtain the same results with a simple array just by putting a factor between its indices:
int jimmy [3][5];   // is equivalent to
int jimmy [15]; // (3 * 5 = 15)


With the only difference that with multidimensional arrays the compiler remembers the depth of each imaginary dimension for us. Take as example these two pieces of code, with both exactly the same result. One uses a bidimensional array and the other one uses a simple array:


#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];
int n,m;

int main ()
{
for (n=0;n<HEIGHT;n++)
for (m=0;m<WIDTH;m++)
{
jimmy[n][m]=(n+1)*(m+1);
}
return 0;
}

None of the two source codes above produce any output on the screen, but both assign values to the memory block called jimmy in the following way:



We have used "defined constants" (#define) to simplify possible future modifications of the program. For example, in case that we decided to enlarge the array to a height of 4 instead of 3 it could be done simply by changing the line:
#define HEIGHT 3 

to:
#define HEIGHT 4 

with no need to make any other modifications to the program.

No comments: