Learn C++
#include "arrayspointers/multidim_arrays.hpp"

Multidimensional Arrays in C++

//concept

Multidimensional arrays nest the same idea: int grid[3][4]; is three rows of four ints, still one flat contiguous block in row-major order. Indexing grid[r][c] walks rows then columns, and nested loops (outer rows, inner columns) are the natural traversal.

Only the first dimension may be deduced from an initializer, and passing them to functions requires all but the first dimension in the signature (void f(int m[][4])) — another reason modern code reaches for vector<vector<int>> or flat vectors with manual indexing.

//how it works
1

Rows of rows, one block

int grid[3][4]; holds 12 ints contiguously, row after row — grid[1][0] sits right after grid[0][3] in memory.

2

Nested loop traversal

Outer loop over rows, inner over columns visits every cell exactly once — the grid-processing standard shape.

3

Partial deduction only

int g[][2]{{1,2},{3,4}}; deduces 2 rows, but the column count must always be spelled out.

4

Function signatures pin dimensions

A parameter int m[][4] hard-codes 4 columns — mismatched widths won't compile, unlike flat-pointer hacks.

//example
#include <iostream>
 
int main() {
int grid[2][3]{{1, 2, 3}, {4, 5, 6}};
int sum = 0;
for (int r = 0; r < 2; ++r) {
for (int c = 0; c < 3; ++c) {
sum += grid[r][c];
}
}
std::cout << sum << std::endl;
return 0;
}
Output
21
1The nested braced lists fill row 0 with 1,2,3 and row 1 with 4,5,6.
2The double loop visits all six cells, accumulating 1+2+3+4+5+6.
321 prints — the sum of every element in the grid.
//use cases
Boards, grids, and matrices in games and simulations
Image pixels as height-by-width channel arrays
Test fixtures with small fixed tables of expected values
Knowing when to graduate to vector<vector<int>> for dynamic sizes

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.