The Analogy: The Spreadsheet and the Chess Board
A one-dimensional array is a single row of pigeonholes. A two-dimensional array is a spreadsheet: rows down, columns across, and you name a cell by giving both — grid[2][3] is row 2, column 3.
The important thing to understand is that the spreadsheet is a polite fiction. Memory is one long line; there are no rows in hardware. A 3x4 array is really twelve consecutive slots, and the compiler translates grid[2][3] into "slot number 2 x 4 + 3 = 11". The rows are laid out one after another — all of row 0, then all of row 1, then all of row 2. This is called row-major order, and knowing it explains both the syntax rules and a surprising performance effect later in this lesson.
Syntax or Core Structure
#include <iostream>
#include <array>
int main() {
// Declaration: [rows][columns]
int grid[3][4]{}; // 3 rows, 4 columns, all zero
// Initialised row by row -- the inner braces are the rows
int board[3][3]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Access needs both indices
std::cout << board[0][0] << "\n"; // 1 -- top left
std::cout << board[1][2] << "\n"; // 6 -- row 1, column 2
std::cout << board[2][2] << "\n"; // 9 -- bottom right
board[1][1] = 99; // assign to the centre
// Walking it: outer loop rows, inner loop columns
for (std::size_t r = 0; r < 3; ++r) {
for (std::size_t c = 0; c < 3; ++c) {
std::cout << board[r][c] << "\t";
}
std::cout << "\n";
}
// Three dimensions work the same way
int cube[2][3][4]{}; // 2 layers of 3x4
cube[1][2][3] = 7;
// The modern equivalent: an array of arrays
std::array<std::array<int, 3>, 3> modern{{
{1, 2, 3}, {4, 5, 6}, {7, 8, 9}
}};
std::cout << modern[1][1] << " of " << modern.size() << " rows\n";
return 0;
}
Read the type inside out: std::array<std::array<int, 3>, 3> is "an array of 3 things, each of which is an array of 3 ints". The doubled outer braces in its initialiser are a quirk of nested aggregate initialisation.
Technical Depth: Row-Major Layout and What It Costs
It really is one flat block
int grid[3][4]{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};
// Proof: read it as a flat array of 12
int* flat = &grid[0][0];
for (int i = 0; i < 12; ++i) { std::cout << flat[i] << " "; }
// 1 2 3 4 5 6 7 8 9 10 11 12 -- rows laid end to end
std::cout << sizeof(grid) << "\n"; // 48 = 12 ints x 4 bytes
std::cout << sizeof(grid[0]) << "\n"; // 16 = one row of 4 ints
The address of grid[r][c] is base + (r * columns + c) * sizeof(int). That formula needs to know the column count but not the row count — which is exactly why the next rule exists.
Passing to a function: all dimensions but the first
void print(int grid[][4], int rows) { // column count REQUIRED, rows optional
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < 4; ++c) { std::cout << grid[r][c] << " "; }
std::cout << "\n";
}
}
void broken(int grid[][], int rows, int cols); // ERROR: cannot omit columns
// Templates keep both dimensions, for any size
template <std::size_t R, std::size_t C>
void printAny(const int (&grid)[R][C]) { // a reference to an array
for (std::size_t r = 0; r < R; ++r) {
for (std::size_t c = 0; c < C; ++c) { std::cout << grid[r][c] << " "; }
std::cout << "\n";
}
}
// Or use std::array and let it carry its own size
void printModern(const std::array<std::array<int, 4>, 3>& grid);
Without the column count the compiler cannot compute r * columns + c, so it is not optional. This inflexibility — a function that only works for 4-column grids — is the main practical reason real code uses std::vector or a flat array with manual indexing instead.
Loop order changes the speed
// FAST: walks memory in order, so each cache line fetch serves many reads
for (int r = 0; r < Rows; ++r)
for (int c = 0; c < Cols; ++c)
total += grid[r][c];
// SLOW: jumps a whole row between reads, wasting most of every cache line
for (int c = 0; c < Cols; ++c)
for (int r = 0; r < Rows; ++r)
total += grid[r][c];
Both are correct. On a large grid the first can be several times faster, because the CPU loads memory in chunks (cache lines) and the row-major layout means consecutive columns are adjacent. Rows outermost, columns innermost — swapping them is a real and measurable mistake on big data.
Runtime sizes: use a vector, or flatten
#include <vector>
// A vector of vectors: rows can even differ in length
int rows{3}, cols{4};
std::vector<std::vector<int>> grid(rows, std::vector<int>(cols, 0));
grid[1][2] = 7;
grid.push_back(std::vector<int>(2, 9)); // a ragged row -- perfectly legal
// Flat vector with manual indexing: one allocation, best cache behaviour
std::vector<int> flat(rows * cols, 0);
auto at = [cols](int r, int c) { return r * cols + c; };
flat[at(1, 2)] = 7;
The vector-of-vectors is easier to read and allows ragged rows, at the cost of one allocation per row and rows scattered around the heap. The flat version is what performance-sensitive code uses: a single contiguous block with an index helper. Both are far more flexible than int grid[3][4].
Comparison
int g[3][4] | std::array nested | vector<vector<int>> | flat vector | |
|---|---|---|---|---|
| Size decided | compile time | compile time | runtime | runtime |
| Rows contiguous | yes | yes | no | yes |
| Ragged rows | no | no | yes | no |
| Allocations | none | none | one per row | one |
| Passing to functions | needs the column count | carries its size | easy | easy |
| Best for | small fixed grids | small fixed grids | readability, ragged data | large or hot data |
Real World Example: Noughts and Crosses
#include <iostream>
#include <array>
using Board = std::array<std::array<char, 3>, 3>;
void draw(const Board& b) {
std::cout << "\n 0 1 2\n";
for (std::size_t r = 0; r < 3; ++r) {
std::cout << r << " ";
for (std::size_t c = 0; c < 3; ++c) {
std::cout << b[r][c] << (c < 2 ? "|" : "");
}
std::cout << "\n";
if (r < 2) { std::cout << " -+-+-\n"; }
}
}
char winner(const Board& b) {
// Rows and columns in one pass -- the symmetry of [r][c] and [c][r]
for (std::size_t i = 0; i < 3; ++i) {
if (b[i][0] != ' ' && b[i][0] == b[i][1] && b[i][1] == b[i][2]) {
return b[i][0];
}
if (b[0][i] != ' ' && b[0][i] == b[1][i] && b[1][i] == b[2][i]) {
return b[0][i];
}
}
// The two diagonals
if (b[1][1] != ' ') {
if (b[0][0] == b[1][1] && b[1][1] == b[2][2]) { return b[1][1]; }
if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) { return b[1][1]; }
}
return ' ';
}
bool full(const Board& b) {
for (const auto& row : b) { // each row is itself an array
for (const char cell : row) {
if (cell == ' ') { return false; }
}
}
return true;
}
int main() {
Board board{};
for (auto& row : board) { row.fill(' '); } // std::array has fill()
char player{'X'};
while (winner(board) == ' ' && !full(board)) {
draw(board);
std::cout << "Player " << player << " -- row and column: ";
int r{}, c{};
if (!(std::cin >> r >> c)) { break; }
// Bounds check BEFORE indexing -- this is user input
if (r < 0 || r > 2 || c < 0 || c > 2) {
std::cout << "Off the board.\n";
continue;
}
if (board[r][c] != ' ') {
std::cout << "Already taken.\n";
continue;
}
board[r][c] = player;
player = (player == 'X') ? 'O' : 'X'; // swap turns
}
draw(board);
const char w = winner(board);
std::cout << (w == ' ' ? "\nDraw.\n" : std::string("\n") + w + " wins.\n");
return 0;
}
The using Board = ... alias is what makes this readable — writing the full nested type in four signatures would be unbearable. winner exploits the symmetry of the layout: swapping the indices from b[i][0] to b[0][i] turns a row check into a column check, so one loop covers both. full uses a nested range-based loop because it needs no positions, and the outer variable is const auto& because each row is a whole array that would otherwise be copied. Most importantly, the user's row and column are range-checked before they reach board[r][c] — with a raw char[3][3] and no check, typing 5 5 would write into unrelated memory.
Common Mistakes
grid[r, c]instead ofgrid[r][c]. Before C++23 the comma version compiles to something meaningless.- Omitting the column count in a function parameter.
int g[][]does not compile. - Swapping rows and columns in the declaration versus the loops, so a 3x5 grid is walked as 5x3 — reading out of bounds on every pass.
- Columns outermost in the loop nest. Correct but needlessly slow on large data.
- Assuming
sizeof(grid) / sizeof(grid[0])gives the column count. It gives the row count; dividesizeof(grid[0]) / sizeof(grid[0][0])for columns. - Not bounds-checking user-supplied indices before using them.
- Expecting a
vector<vector<int>>to be contiguous. Each row is a separate heap allocation. - Forgetting to initialise:
int grid[3][4];is twelve garbage values. Add{}.
Best Practices
- Alias the type:
using Board = std::array<std::array<char, 3>, 3>;and use it everywhere. - Rows in the outer loop, columns in the inner. Match the memory layout.
- Name the dimensions as
constexprvalues rather than repeating3and4throughout. - Prefer
std::arraynesting for fixed grids, a flatstd::vectorwith an index helper for large or runtime-sized ones. - Validate every index that came from outside before you use it.
- Stop at two dimensions where you can. Three-plus is usually better modelled as a struct or a flat buffer.
- Pass by
constreference, never by value — a nestedstd::arraycopies its entire contents.
Practice Exercises
- Transpose: Fill a 3x4 grid, print it, then print its 4x3 transpose. Then explain in a comment why an in-place transpose only works on a square grid.
- Seat booking: Model a 5x8 cinema as a 2D array of
char, let the user book a seat by row and column with full validation, and print a map showing free and taken seats plus the number remaining. - Cache experiment: Sum a 2000x2000
std::vector<int>flat buffer twice — once rows-outermost, once columns-outermost — timing both withstd::chrono. Report the ratio you measure. - Magic square checker: Write
bool isMagic(const int grid[][4], int rows)that returns true only when every row, every column and both diagonals sum to the same value. Test it on a genuine 4x4 magic square and on one with two entries swapped. Then try to change the parameter toconst int grid[][], record the compiler error, and explain in a comment why the first dimension may be left out but the second may not.