Multidimensional Arrays
A two-dimensional built-in array is stored contiguously in row-major order in both C and C++.
What is Multidimensional Arrays?
A two-dimensional built-in array is stored contiguously in row-major order in both C and C++.
Traverse a row-major matrix and calculate row totals.
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.
C and C++ code examples
main.c
#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
C++
main.cpp
#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.
C
Ownership and cleanup are conventions enforced by the programmer.
C++
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.