cpp / intermediate
Snippet
Two-Dimensional Data Initialization
Multidimensional arrays are stored in row-major order in memory. Initializing them with nested braces improves code clarity by visually mapping the data to its logical grid structure.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>int main() {// Initializing a 2x3 matrix using nested brace listsint grid[2][3] = {{1, 2, 3},{4, 5, 6}};for (int i = 0; i < 2; ++i) {for (int j = 0; j < 3; ++j) {std::cout << grid[i][j] << " ";}std::cout << "\n";}return 0;}
Breakdown
1
int grid[2][3] = { ... };
Defines a 2D array with 2 rows and 3 columns of integers.
2
grid[i][j]
Accesses the element at the i-th row and j-th column.