Multidimensional Arrays
2D Arrays (Matrices)
A 2D array is an array of arrays, often used to represent tabular data like matrices.
In standard C++, the dimensions of a built-in multidimensional array must be compile-time constants.
// Declaration
int matrix[3][4]; // 3 rows, 4 columns
// Initialization
int grid[2][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};
Accessing Elements
Visualization of grid[2][3]:
// Get element at row 1, column 2
int value = grid[1][2]; // 6
// Modify element at row 0, column 1
grid[0][1] = 9;
Row | Column 0 | Column 1 | Column 2 |
---|---|---|---|
0 | 1 | 9 | 3 |
1 | 4 | 5 | 6 |
Nested Loops for 2D Arrays
#include <iostream>
using namespace std;
int main() {
int grid[2][3] = { {1, 9, 3}, {4, 5, 6} };
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
cout << grid[row][col] << " ";
}
cout << '\n';
}
}
1 9 3 4 5 6
3D and Higher Dimensions
C++ supports arrays with more than two dimensions. For example, a 3D array can represent volumetric data or RGB images.
// 3D array (e.g., for RGB image data)
int image[480][640][3]; // Height × Width × Color channels
// Accessing pixel at (10,20)
int red = image[10][20][0];
int green = image[10][20][1];
int blue = image[10][20][2];
Passing Multidimensional Arrays to Functions
All but the first dimension must be known in the parameter type. Alternatives include references to arrays or passing a flat pointer with explicit row/column counts.
// Dimension after the first must be fixed in the parameter type
void print(const int a[][3], int rows) {
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < 3; ++c) {
std::cout << a[r][c] << ' ';
}
std::cout << '\n';
}
}
// Or pass a flat pointer with sizes and index manually
void printFlat(const int* a, int rows, int cols) {
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
std::cout << a[r * cols + c] << ' ';
}
std::cout << '\n';
}
}
int main() {
int grid[2][3] = { {1,2,3}, {4,5,6} };
print(grid, 2);
printFlat(&grid[0][0], 2, 3);
}
Memory Layout & Indexing
For a 2D array int a[R][C], the address of a[r][c] equals &a[0][0] + (r * C + c). This is why the second dimension (C) must be known for correct indexing.
Row-major layout: all columns of row 0, then all columns of row 1, and so on.
Real-World Applications
- Representing game boards (chess, tic-tac-toe)
- Image and video processing
- Scientific computing (matrices, tensors)
- Tabular data storage
- 3D graphics and voxel-based data