Multidimensional Arrays
Traverse a row-major matrix and calculate row totals.
What is Multidimensional Arrays?
A two-dimensional built-in array is stored contiguously in row-major order in both C and C++.
Important points
- Every pointer must refer to a live compatible object or be null.
- Pair each owned allocation with exactly one release.
- Prefer clear ownership and const-correct interfaces.
See how it works
Point at a cell to see its row and column, and where it sits in memory, where all rows are stored one after another.
C and C++ code examples
#include <stdio.h>
int main(void) {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int row = 0; row < 2; ++row) {
int total = 0;
for (int column = 0; column < 3; ++column) total += matrix[row][column];
printf("row %d=%d\n", row, total);
}
return 0;
}
row 0=6
row 1=15
#include <array>
#include <iostream>
int main() {
std::array<std::array<int, 3>, 2> matrix{{{{1, 2, 3}}, {{4, 5, 6}}}};
for (std::size_t row = 0; row < matrix.size(); ++row) {
int total = 0;
for (int value : matrix[row]) total += value;
std::cout << "row " << row << '=' << total << '\n';
}
}
row 0=6
row 1=15
C and C++ comparison
A C function parameter must know every dimension except the first. std::array preserves dimensions in its type and exposes bounds-aware alternatives such as at.
Ownership and cleanup are conventions enforced by the programmer.
Containers and RAII types can encode ownership and cleanup in object lifetimes.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Test null and allocation-failure paths.
- Run with AddressSanitizer and UndefinedBehaviorSanitizer.
- Document whether every pointer owns or only observes its object.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Row Sums Add up every row of a grid. Easy
- Minesweeper Neighbor Counts Annotate a rectangular board. Medium