Multi-dimensional arrays, often called a matrix, are possible in C++. C/C++ treats them as an array of arrays. Because of how they are defined, each array within the array will be of the same size. This actually makes them easier to work with.
To define them, you use two sets of brackets, and can think of them in a setting of rows and columns like:
dataType arrayName[ROW_SIZE][COLUMN_SIZE];
Thus, and actual defining of a variable might be something like:
int matrix[10][5];
You can assign values to your variable indexes, with something like the example below. Notice the extra sets of braces for each array within the outer array, and the commas between the inner arrays.
int matrix[][] = {
{ 1,2,3,4,5 },
{ 2,4,6,8,10},
{ 1,3,5,7,9},
{ 5,10,15,20,25},
{ 3,6,9,12,15}
}
To assign a value to a multidimensional array, you need to specify both indexes.
int matrix[5][5];
matrix[0][3] = 10;
Processing A Matrix
Usually, to process a matrix, you will use a nested for loop. Consider the following blocks of code which create a matrix, assign a value, and then print it out.
const int ROW_SIZE = 10;
const int COLUM_SIZE = 10;
int matrix[ROW_SIZE][COLUM_SIZE];
for (int j, i = 0; i < ROW_SIZE; i++)
{
for (j = 0; j < COLUM_SIZE; j++)
{
matrix[i][j] = rand() % 1000;
}
}
for (int column, row = 0; row < ROW_SIZE; row++)
{
for (column = 0; column < COLUM_SIZE; column++)
{
cout << matrix[row][column] << "\t";
}
cout << endl;
}
Passing a Matrix to a Function
When you pass a multidimensional array, the second, and any other dimensions, sizes need to specified in the call.
const int COLUMN_SIZE = 5;
int sum(const int array[][COLUMN_SIZE], int row_size);
Here I’ve just shown the function prototype, but you can get the idea from that. We used const as we don’t want to change the matrix, just like we can use it to not change a regular array, and we pass in the row size as a separate variable.
We used a global for the column size, assuming that this is a simple program and a single global will work for it. For more complex programs, we might need to find a better variable name, but the idea works the same.
Two Dimensional Arrays in C++ was originally found on Access 2 Learn