Sahaj.blogs
22 Nov 2023 · StudyPhase 2 · C++

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 its size(), 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 throws std::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]: 1

#cpp#arrays

Sources

  1. Array declaration — cppreference.com
  2. std::array — cppreference.com
  3. Introduction to std::array — LearnCpp.com