C++ · Arrays
C-style arrays, std::array, 2D arrays, out-of-bounds risk, and why .at() exists.
- A C-style array
int a[5];has a fixed size, sits in one contiguous block of memory, and decays to a pointer when passed to a function, which loses the size. std::array<int, 5>has the same performance but knows itssize(), can be copied, and works with STL algorithms.a[i]does no bounds checking, so reading past the end is undefined behaviour..at(i)checks and throwsstd::out_of_range.- 2D arrays are stored row by row (row-major), the same layout NumPy uses by default.
#include <array>
#include <iostream>
#include <stdexcept>
int main() {
int raw[5] = {5, 3, 8, 1, 9};
std::cout << "raw size via sizeof: " << sizeof(raw) / sizeof(raw[0]) << '\n';
std::array<int, 5> a{5, 3, 8, 1, 9};
int total = 0;
for (int v : a) total += v;
std::cout << "std::array size " << a.size() << ", sum " << total << '\n';
try {
std::cout << a.at(10) << '\n';
} catch (const std::out_of_range& e) {
std::cout << "out_of_range caught\n";
}
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (auto& row : grid) {
for (int v : row) std::cout << v << ' ';
std::cout << '\n';
}
std::cout << "row-major: grid[1][0] is right after grid[0][2]: "
<< (&grid[1][0] == &grid[0][2] + 1) << '\n';
}
Output:
raw size via sizeof: 5
std::array size 5, sum 26
out_of_range caught
1 2 3
4 5 6
row-major: grid[1][0] is right after grid[0][2]: 1Sources
- Array declaration — cppreference.com
- std::array — cppreference.com
- Introduction to std::array — LearnCpp.com