Topic 22 of 83
Multi-Dimensional Arrays
Overview
Multi-dimensional arrays are arrays of arrays. A 2D array represents a matrix or grid, which is incredibly useful for rendering maps, boards, or mathematical computations.
Syntax
cpp
// 2D Array: Type name[rows][cols]
int matrix[2][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};
// Accessing elements
int val = matrix[1][2]; // 6Common Pitfalls
- Confusing row and column indices (`matrix[col][row]` instead of `matrix[row][col]`).
Interview Tips
- When passing a 2D array to a function, you MUST specify the number of columns in the parameter: `void printMatrix(int mat[][3], int rows)`.
Real-World Example
Iterating through a 2D grid.
example
cpp
#include <iostream>
using namespace std;
int main() {
int grid[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
cout << grid[row][col] << " ";
}
cout << "\n";
}
return 0;
}