cpp / intermediate
Snippet
Grid Storage with Nested Arrays
Multidimensional arrays in C++ are stored in row-major order. This means all elements of a row are contiguous in memory. Nested loops are the standard way to traverse these structures using row and column indices.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>void renderGrid() {// A 2x3 matrix of integersint grid[2][3] = {{1, 2, 3},{4, 5, 6}};for (int r = 0; r < 2; r++) {for (int c = 0; c < 3; c++) {std::cout << grid[r][c] << " ";}std::cout << std::endl;}}
Breakdown
1
int grid[2][3]
Declares an array of 2 arrays, each containing 3 integers.
2
grid[r][c]
Uses two indices to access a specific element in the 2D memory layout.