Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. C arrays
    4. Arrays decay to pointers
    5. std::array: an array that knows its size
    6. [] trusts you, .at() checks
    7. std::span: one function for every array
    8. Part of an array: subspan
    9. 2D data stored flat
    10. Which one should I use?
    11. Under the hood
    12. Common pitfalls
    13. sizeof on an array parameter
    14. Passing the wrong count with a pointer
    15. Try it yourself

    Module 2 · Memory

    2.4Arrays, std::array and std::span

    Store a fixed number of values side by side with a C array or std::array, check indexes with .at(), and write one function that works on any of them with std::span.

    About 25 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. C arrays
    4. Arrays decay to pointers
    5. std::array: an array that knows its size
    6. [] trusts you, .at() checks
    7. std::span: one function for every array
    8. Part of an array: subspan
    9. 2D data stored flat
    10. Which one should I use?
    11. Under the hood
    12. Common pitfalls
    13. sizeof on an array parameter
    14. Passing the wrong count with a pointer
    15. Try it yourself

    Key terms

    array
    A fixed number of values of one type, stored side by side in memory with no gaps.
    element
    One value in an array. Elements are numbered from 0, so the last one is at size − 1.
    index
    The number of an element, written in square brackets: a[2] is the third element.
    C array (T[N])
    The array built into the language, like int counts[4]. It doesn't carry its size with it.
    decay
    The automatic conversion of a C array to a pointer to its first element. The size is lost.
    std::array<T, N>
    A standard library array of N elements of type T. Same memory as a C array, but it knows its size and can be copied.
    out of bounds
    An index outside 0 to size − 1. Reading or writing there is undefined behavior.
    .at(i)
    Element access that checks the index and throws std::out_of_range if it's out of bounds.
    exception
    A way to report an error by jumping out of the current code. If nothing catches it, the program stops. Module 5 covers exceptions.
    std::span<T>
    A view of elements that live somewhere else: a pointer to the first one plus a count. It owns nothing and copies nothing.
    contiguous
    Stored side by side in one block of memory, with no gaps. Arrays, std::array and std::vector are contiguous.
    subspan
    A smaller span over part of a span: s.subspan(offset, count).
    row-major order
    Storing a 2D grid flat, one row after another. Element (row, column) is at index row * width + column.

    Many programs work with a fixed number of values of one type: the counts of the four DNA bases, the three color channels of a pixel, a row of sensor readings. An array stores them side by side in memory, and you pick one by its number. C++ has two kinds of array, and a third type, std::span, that lets one function work with either.

    In 30 seconds

    • int counts[4] is a C array: four ints side by side. Pass it to a function and it turns into a pointer, losing its size.
    • std::array<int, 4> is the same four ints, but it knows its size (.size()), can be copied, and has .at(), which checks the index.
    • Reading past the end with [] is undefined behavior. The sanitizers catch it while you test.
    • std::span<const int> is a view: a pointer plus a count. A function that takes a span accepts a C array, a std::array or a std::vector.

    C arrays

    Write the number of elements in square brackets after the name. The values in braces fill the elements in order. Elements are numbered from 0, so an array of 4 has elements 0 to 3.

    #include <iterator>
    #include <print>
    
    int counts[4] = {12, 7, 9, 3}; // A, C, G, T
    counts[1] += 1;
    std::println("A: {}, C: {}", counts[0], counts[1]);
    std::println("{} elements, {} bytes", std::size(counts), sizeof(counts));

    Output

    A: 12, C: 8
    4 elements, 16 bytes

    sizeof gives the size of the whole array in bytes: 4 elements of 4 bytes each on this platform. std::size (from <iterator>) gives the number of elements. If you write = {}, every element starts at 0.

    Arrays decay to pointers

    When you pass a C array to a function, C++ converts it to a pointer to its first element. This is called decay. The function receives only an address, so it can’t know how many elements there are: you have to pass the count yourself.

    #include <cstddef>
    #include <print>
    
    int sum(const int* values, std::size_t count) {
        std::println("inside sum: {} bytes", sizeof(values));
        int total = 0;
        for (std::size_t i = 0; i < count; ++i) {
            total += values[i]; // [] works on a pointer too
        }
        return total;
    }
    
    int main() {
        int counts[4] = {12, 7, 9, 3};
        std::println("in main: {} bytes", sizeof(counts));
        std::println("total: {}", sum(counts, 4));
    }

    Output

    in main: 16 bytes
    inside sum: 8 bytes
    total: 31

    Inside sum, values is a pointer (8 bytes here), not the array. values[i] on a pointer means *(values + i), the pointer arithmetic from the last lesson. Nothing checks that the count you pass matches the array. That’s the main weakness of C arrays, and the next two types fix it.

    std::array: an array that knows its size

    std::array<int, 4> (from <array>) holds the same four ints, with no extra bytes. The angle brackets give the element type and the count, and the count must be known when the program is compiled.

    #include <array>
    #include <print>
    
    std::array<int, 4> counts = {12, 7, 9, 3};
    std::println("{} elements, {} bytes", counts.size(), sizeof(counts));
    
    std::array<int, 4> backup = counts; // copies all four elements
    counts[0] = 0;
    std::println("{} {}", counts, backup);
    std::println("equal: {}", counts == backup);

    Output

    4 elements, 16 bytes
    [0, 7, 9, 3] [12, 7, 9, 3]
    equal: false

    A std::array copies like an int does, compares with ==, prints with std::println, and keeps its size when you pass it to a function. Use it wherever you’d use a C array.

    [] trusts you, .at() checks

    a[i] reads element i without any check you can rely on. With an index past the end, it usually reads whatever memory comes next. That’s undefined behavior, and the sanitizers catch it when the program runs:

    #include <print>
    
    int counts[4] = {12, 7, 9, 3};
    int total = 0;
    for (int i = 0; i <= 4; ++i) { // <= runs one step too far
        total += counts[i];
    }
    std::println("{}", total);

    This fails when it runs

    main.cpp:6:22: runtime error: index 4 out of bounds for type 'int [4]'

    The fix is i < 4. When an index comes from outside your code, such as user input or a file, use .at(i) on a std::array. It checks the index and throws a std::out_of_range exception if it’s out of bounds. An exception jumps out of the current code; if nothing catches it, the program stops with a message:

    #include <array>
    #include <print>
    
    std::array<int, 4> counts = {12, 7, 9, 3};
    std::println("{}", counts.at(4));

    This fails when it runs

    terminate called after throwing an instance of 'std::out_of_range'
      what():  array::at: __n (which is 4) >= _Nm (which is 4)

    To handle the error instead, wrap the code in try and catch the exception. Module 5 covers exceptions; for now, this is all you need:

    #include <array>
    #include <print>
    #include <stdexcept>
    
    std::array<int, 4> counts = {12, 7, 9, 3};
    try {
        std::println("{}", counts.at(4));
    } catch (const std::out_of_range&) {
        std::println("There's no element 4: the indexes are 0 to 3.");
    }

    Output

    There's no element 4: the indexes are 0 to 3.

    Key ideaUse [] when the index is right by construction

    In a loop from 0 to size() - 1, [] is correct and fast. Use .at() when the index comes from data you don’t control, and build with the sanitizers while you test either way.

    std::span: one function for every array

    A function that takes const std::array<double, 3>& only accepts arrays of exactly 3 doubles. std::span (from <span>) removes that limit. A std::span<const double> is a view: a pointer to the first element and a count. It owns nothing and copies nothing, and it can be made from any contiguous run of doubles.

    #include <array>
    #include <print>
    #include <span>
    #include <vector>
    
    double average(std::span<const double> values) {
        double total = 0.0;
        for (double v : values) {
            total += v;
        }
        return total / static_cast<double>(values.size());
    }
    
    int main() {
        double c_array[3] = {1.0, 2.0, 3.0};
        std::array<double, 2> fixed = {4.0, 6.0};
        std::vector<double> growing = {0.5, 1.5, 2.5, 3.5};
        std::println("{} {} {}", average(c_array), average(fixed),
                     average(growing));
    }

    Output

    2 5 2

    Each call builds a span from the argument, with the right count, so the C array doesn’t lose its size on the way in. std::vector, which Module 3 covers in full, is an array that can grow.

    const in std::span<const double> means the function can only read the elements. Drop it, std::span<double>, and the function can change the caller’s elements, like a reference.

    Part of an array: subspan

    s.subspan(offset, count) gives a smaller span: count elements starting at index offset. It still points into the same memory, so changing an element through it changes the original array.

    #include <array>
    #include <print>
    #include <span>
    
    std::array<int, 6> readings = {3, 8, 8, 9, 2, 5};
    std::span<int> all = readings;
    std::span<int> middle = all.subspan(1, 3);
    std::println("{} has {} elements", middle, middle.size());
    middle[0] = 0;
    std::println("{}", readings);

    Output

    [8, 8, 9] has 3 elements
    [3, 0, 8, 9, 2, 5]
    After middle = all.subspan(1, 3)readings is a std::array of six ints, 3, 0, 8, 9, 2, 5, stored in main's stack frame. middle is a std::span: its data field points at element 1 of readings (the 0), and its size field holds 3. The span copies nothing; it views elements 1 to 3 of the array.Stackreadings, also on the stackmiddle: std::span<int>datasize3std::array<int, 6>308925
    After middle = all.subspan(1, 3). readings is a std::array of six ints, 3, 0, 8, 9, 2, 5, stored in main's stack frame. middle is a std::span: its data field points at element 1 of readings (the 0), and its size field holds 3. The span copies nothing; it views elements 1 to 3 of the array.

    2D data stored flat

    An image is a grid of pixels, but memory is one long line. The usual way to store a grid is row-major order: row 0, then row 1, and so on, in one array. The pixel at (row, column) is at index row * width + column, and a whole row is a subspan.

    #include <array>
    #include <cstddef>
    #include <print>
    #include <span>
    
    constexpr std::size_t width = 3;
    constexpr std::size_t height = 2;
    std::array<int, width * height> pixels = {10, 20, 30,  // row 0
                                              40, 50, 60}; // row 1
    
    std::println("row 1, column 2: {}", pixels[1 * width + 2]);
    std::span<int> image = pixels;
    std::println("row 1: {}", image.subspan(1 * width, width));

    Output

    row 1, column 2: 60
    row 1: [40, 50, 60]

    You’ll use this layout for images, matrices and model weights later in the course: one contiguous block is fast to read and easy to pass around as a span.

    Which one should I use?

    WhatWhenWhyHow
    std::arrayThe number of elements is fixed and known when you write the code.Same memory and speed as a C array, but it knows its size, copies, compares and has .at().std::array<int, 4> counts = {};
    std::vectorThe number of elements is only known at run time, or changes.It grows as needed and frees its memory for you. Module 3 covers it.std::vector<double> readings;
    std::span parameterA function reads or changes a run of elements it doesn’t own.One function accepts C arrays, std::array and std::vector, with the size included.void f(std::span<const int> values)
    C arrayCode that has to talk to a C library, or old code.It’s what C uses, but it decays to a pointer and loses its size.int counts[4] = {};

    Rule of thumb: store fixed-size data in a std::array and growing data in a std::vector, and write functions that take std::span<const T>.

    Under the hood

    All three types point to the same kind of memory: elements side by side, with no gaps. A C array and a std::array are that memory, so their size is the size of the elements. A span is only a pointer and a count, so it’s 16 bytes on this platform, however many elements it views.

    #include <array>
    #include <print>
    #include <span>
    
    int c_array[6] = {};
    std::array<int, 6> fixed = {};
    std::span<int> view = fixed;
    std::println("{} {} {}", sizeof(c_array), sizeof(fixed), sizeof(view));

    Output

    24 24 16
    Six ints, and a span over them
    Six ints, and a span over them: each row is one value; each cell's width is its size in bytes.
    Value01234567891011121314151617181920212223Size
    int[6][0]4 bytes[1]4 bytes[2]4 bytes[3]4 bytes[4]4 bytes[5]4 bytes24 bytes
    std::array<int, 6>[0]4 bytes[1]4 bytes[2]4 bytes[3]4 bytes[4]4 bytes[5]4 bytes24 bytes
    std::span<int>data pointer8 bytessize8 bytes16 bytes

    int[6] and std::array<int, 6> are both 24 bytes: six 4-byte ints, one after another. A std::span<int> is 16 bytes on this platform: an 8-byte pointer to the first element and an 8-byte count.

    Element i is at the address of element 0 plus i * sizeof(int) bytes. That’s why indexing is fast, and also why nothing stops an index from running past the end: the computer adds and reads.

    PerformancePass spans by value

    A span is only a pointer and a count, so copying one costs almost nothing. Take std::span<const T>, not const std::span<const T>&.

    Common pitfalls

    sizeof on an array parameter

    A parameter written as int values[] looks like an array, but it’s a pointer: the array decayed on the way in. sizeof(values) gives the size of the pointer, not of the array. GCC and Clang both warn about this, so with warnings as errors it doesn’t compile:

    #include <cstddef>
    #include <print>
    
    std::size_t count(int values[]) {
        return sizeof(values) / sizeof(values[0]);
    }
    
    int main() {
        int counts[4] = {12, 7, 9, 3};
        std::println("{}", count(counts));
    }

    The compiler rejects this

    main.cpp: In function ‘std::size_t count(int*)’:
    main.cpp:5:19: error: ‘sizeof’ on array function parameter ‘values’ will return size of ‘int*’ [-Werror=sizeof-array-argument]
        5 |     return sizeof(values) / sizeof(values[0]);
          |                  ~^~~~~~~
    main.cpp:4:23: note: declared here
        4 | std::size_t count(int values[]) {
          |                   ~~~~^~~~~~~~
    cc1plus: all warnings being treated as errors

    The fix is to take a std::span<const int> and call values.size().

    Passing the wrong count with a pointer

    With a pointer and a separate count, nothing checks the count. Pass one too many and the function reads past the end of the array. The compiler can’t see it; AddressSanitizer can:

    #include <cstddef>
    #include <print>
    
    int sum(const int* values, std::size_t count) {
        int total = 0;
        for (std::size_t i = 0; i < count; ++i) {
            total += values[i];
        }
        return total;
    }
    
    int main() {
        int counts[4] = {12, 7, 9, 3};
        std::println("{}", sum(counts, 5));
    }

    This fails when it runs

    ERROR: AddressSanitizer: stack-buffer-overflow on address 0x…
    READ of size 4 at 0x… thread T0
        #0 sum(int const*, unsigned long) main.cpp:7
        #1 main main.cpp:14
    
    Address 0x… is located in stack of thread T0 at offset 112 in frame
        #0 main main.cpp:12
    
      This frame has 3 object(s):
        [48, 52) '<unknown>'
        [64, 80) '<unknown>'
        [96, 112) 'counts' (line 13) <== Memory access at offset 112 overflows this variable
          (longjmp and C++ exceptions *are* supported)
    SUMMARY: AddressSanitizer: stack-buffer-overflow main.cpp:7 in sum(int const*, unsigned long)

    Take a std::span<const int> instead and call sum(counts): the span gets the count from the array itself.

    Common pitfallA span doesn't keep its elements alive

    A span is a view, like a reference. If the array or vector it views is destroyed, or a vector moves its elements to grow, the span dangles. Make a span when you need it, usually as a function parameter, rather than storing one for later.

    Try it yourself

    Try it yourself

    A grayscale image 3 pixels wide and 2 rows high is stored flat, in row-major order. Right now row_total returns only the first pixel of the row. Change it to return the sum of all the pixels in that row, using subspan.

    #include <array>
    #include <cstddef>
    #include <print>
    #include <span>
    
    int row_total(std::span<const int> image, std::size_t width, std::size_t row) {
        return image[row * width]; // only the first pixel of the row
    }
    
    int main() {
        std::array<int, 6> image = {10, 20, 30, 40, 50, 60};
        std::println("{} {}", row_total(image, 3, 0), row_total(image, 3, 1));
    }

    Expected output

    60 150
    Show a hint

    image.subspan(row * width, width) is the row you want. Loop over it with a range for and add up the pixels.

    Show a solution
    #include <array>
    #include <cstddef>
    #include <print>
    #include <span>
    
    int row_total(std::span<const int> image, std::size_t width, std::size_t row) {
        int total = 0;
        for (int pixel : image.subspan(row * width, width)) {
            total += pixel;
        }
        return total;
    }
    
    int main() {
        std::array<int, 6> image = {10, 20, 30, 40, 50, 60};
        std::println("{} {}", row_total(image, 3, 0), row_total(image, 3, 1));
    }

    Row r starts at index r * width and has width pixels, so image.subspan(row * width, width) is exactly that row. The function takes std::span<const int>, so it works with the std::array here and would work with a std::vector or a C array too.

    Saved in this browser only.