Skip to content

Chapter 8 of 31

Arrays

Work safely with raw arrays, std::array, multidimensional storage, span, and bounds.

34 minutes 10 quick checksBy Subha Prasad
Lesson 8 of 31Course navigation

Lesson content

Read, practise, then check your understanding

A built-in array stores a fixed number of same-type elements contiguously. Indices run from zero to size minus one; out-of-bounds access is undefined behavior. In most expressions a raw array decays to a pointer, losing its extent.

#include <array>
#include <span>

std::array<int, 4> scores{72, 84, 91, 68};

int total(std::span<const int> values) {
    int result{};
    for (int value : values) result += value;
    return result;
}

std::array<T, N> is a regular fixed-size container with .size(), iterators, comparison, and .at() bounds checking. std::vector is better when size changes at runtime. std::span is a non-owning view that passes contiguous data with its size; the viewed storage must outlive the span.

Multiple dimensions

std::array<std::array<int, 3>, 2> matrix{{
    {1, 2, 3},
    {4, 5, 6}
}};

for (const auto& row : matrix) {
    for (int value : row) { /* use value */ }
}

Built-in multidimensional arrays and nested std::array objects use row-major layout: the rightmost dimension is contiguous. A vector-of-vectors supports irregular rows but is not one contiguous matrix. Choose layout based on ownership, size variability, cache access, and interface needs. Prefer range iteration and algorithms; use indices only when position itself is part of the problem.

Knowledge check

Answer every question correctly to complete this chapter.

What is the first array index?
Which standard type wraps a fixed-size array?
Which container should usually hold a runtime-sized contiguous sequence?
How many elements are in int m[2][3]?
What does std::array::at provide?
What is std::span?
What happens on raw array out-of-bounds access?
How does an array usually pass to a plain function parameter?
Why prefer std::array over a raw fixed array in interfaces?
What is row-major order?

0 of 10 checks passed

Your progress is saved on this device.

Arrays | C++ Lesson | Subha Prasad