C++ · Arrays
Two-dimensional and multidimensional arrays
Understand row and column indices in C++ 2D arrays with row-sum examples, nested traversal and valid-neighbor boundary checks.
Practice this topic in the app Read the lesson in the app
Row and column indices and traversal
int a[2][3] represents 2 rows and 3 columns, 6 integers in total; when accessing a[i][j], both 0≤i<2 and 0≤j<3 must be satisfied.
A C++ multidimensional array is essentially an array of arrays, stored contiguously by row. It is common to use an outer loop to enumerate rows and an inner loop to enumerate columns. To initialize all to zero, write int a[2][3] = {};.
A three-dimensional array a[layer][row][column] can represent multiple tables, and the total number of elements equals the product of the sizes of each dimension. When an array is too large, estimate the memory; in standard C++14, the dimensions of an ordinary array should be compile-time constants, and vector can be used for dynamic sizes.
Row sums and valid neighbors
Example 1: Compute the sum of each row separately
#include <iostream>
using namespace std;
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; ++i) {
int sum = 0;
for (int j = 0; j < 3; ++j) sum += a[i][j];
cout << sum << endl;
}
}Output 6 and 15. sum is reset to zero at the start of each row; if it is placed outside the outer loop, it becomes the cumulative total.
Example 2: Access only valid neighbors
#include <iostream>
using namespace std;
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
int x = 0, y = 0, sum = 0;
for (int d = 0; d < 4; ++d) {
int nx = x + dx[d], ny = y + dy[d];
if (nx >= 0 && nx < 2 && ny >= 0 && ny < 3) sum += a[nx][ny];
}
cout << sum << endl;
}The top-left corner has only two valid neighbors, 4 below and 2 to the right, and outputs 6; the array can be accessed only after checking the boundaries.
Tips
- The number of rows and the number of columns are different, so you cannot copy the same upper limit in both loops.
- Even if the two-dimensional array a[0][3] happens to be close to the next row's memory, it is not a legal cross-row access.
- The space of a multidimensional array is the product of the dimensions; 1000×1000 common 4-byte ints occupy about 4 MB.
Prerequisites
Technical references
Scope note
This lesson is written by InfoCode and is not an official syllabus; the reference level is a site mapping and does not represent official levels, certification or eligibility. Practice records do not establish mastery or eligibility.
Reference level: GESP Level 4 (site mapping)