skip to content

In C++, what does std::array give you over a built-in C array, and how does it differ from std::vector?

level: juniorimportance: must knowfreq 68%

answer

  1. fixed size inside the type
  2. no decay to a pointer
  3. copy, return, size(), at()
  4. inline storage, linear move

basics

~20 s

std::array<T, N> wraps a fixed-size C array: it does not decay to a pointer, can be copied and returned, and offers size(), at() and iterators. Unlike std::vector, its size is fixed at compile time and its elements live inline.

solid answer

~40 s

`std::array<T, N>` is an aggregate holding exactly N elements of `T`, so its elements live wherever the object lives, with no heap allocation. Compared with a raw array, it keeps its size in the type and does not decay to a pointer when passed, so a function taking `const std::array<Emitter, 4>&` still knows there are four. It can be copied, assigned and returned by value, and it offers `size()`, bounds-checked `at()` that throws `std::out_of_range`, iterators and comparison operators. Compared with `std::vector`, the size is a compile-time constant that never changes, there is no capacity or `push_back`, and moving or swapping it is linear in N because each element moves, while a vector moves in constant time by handing over its buffer. Use it for small fixed sets, such as a particle system's four emitters.

code

cpp · 26 lines
cpp
#include <array>
#include <cstdio>

struct Emitter { float x, y; int rate; };

void tick_c(Emitter emitters[4]) {             // really Emitter*: the 4 is ignored
    std::printf("C array parameter: sizeof=%zu\n", sizeof(emitters));
}

void tick(const std::array<Emitter, 4>& emitters) {
    std::printf("std::array parameter: size()=%zu\n", emitters.size());
}

int main() {
    Emitter raw[4] = {};
    tick_c(raw);

    std::array<Emitter, 4> emitters{};           // aggregate: elements inline, no heap
    tick(emitters);
    std::array<Emitter, 4> backup = emitters;    // copyable; a raw array is not
    backup[0].rate = 60;
    std::printf("emitters[0].rate=%d backup[0].rate=%d\n", emitters[0].rate, backup[0].rate);

    auto rates = std::to_array({30, 60, 120});   // C++20: std::array<int, 3>
    std::printf("rates.size()=%zu\n", rates.size());
}

go deeper

for a junior

Name the C array problems std::array fixes: decay to a pointer, no copy or return, no size(). Know that at() checks bounds and operator[] does not.

for a middle

Contrast std::array with std::vector: compile-time size in the type, inline storage, no growth API, and linear move and swap.

for a senior

Watch for large std::array objects on the stack and for APIs templated on N; prefer std::span parameters when callers pass arrays of different sizes.

for a principal

Set guidance for fixed-size data: std::array for small compile-time sets, std::vector for run-time sizes, and span-based interfaces so callers are not tied to either.

## What std::array is `std::array<T, N>`, from the `<array>` header since C++11, is a class template for fixed-size sequences. The standard describes it as a contiguous container and an aggregate: it stores exactly `N` elements of type `T`, `size() == N` always holds, and it can be list-initialized with up to `N` values, just like a C array. It does not allocate. The elements live wherever the `std::array` object lives: on the stack, inside another object, or in static storage. In a particle system with four fixed emitters, `std::array<Emitter, 4> emitters{};` keeps four emitters inline in the system object, with no heap block and no pointer to chase. ## What it fixes compared with a C array | Behaviour | `Emitter raw[4]` | `std::array<Emitter, 4>` | |---|---|---| | Passed to a function | decays to `Emitter*`; the 4 is lost | passed by reference or value as a whole; the size stays in the type | | Copy and assignment | cannot be copy-assigned (`raw2 = raw` is ill-formed) | copy and assignment work element by element | | Returned from a function | not allowed | allowed | | Size query | `std::size(raw)` (C++17), only where the array has not decayed | `size()`, usable in constant expressions | | Bounds-checked access | none | `at(i)` throws `std::out_of_range` | | Comparison | `raw1 == raw2` compared addresses; deprecated as of C++23, ill-formed in C++26 | `==` compares elements; C++20 adds `<=>` | The decay row is the one interviewers probe. A parameter declared `Emitter emitters[4]` is adjusted to `Emitter*`, so `sizeof(emitters)` inside the function is the size of a pointer; clang even warns with `-Wsizeof-array-argument`. ## How it differs from std::vector - **Size**: fixed at compile time and part of the type. `std::array<int, 3>` and `std::array<int, 4>` are different types, so a function must be a template over `N` or take a `std::span` to accept both. - **Storage**: inline in the object, so a large `std::array` on the stack can overflow it, where a vector keeps only three pointers' worth of state there. - **No growth API**: there is no `push_back`, `insert`, `capacity()` or `reserve()`. - **Move and swap are linear**: the standard lists move construction and `swap` as linear for `array` and constant for the other containers. A `std::vector` moves by handing over its buffer pointer; a `std::array<std::string, 1000>` moves a thousand strings one by one. - **Not allocator-aware**: it takes no allocator. ## Initialization details - `std::array<int, 3> a{1, 2, 3};` is aggregate initialization; missing elements are value-initialized, so `std::array<int, 3> z{};` is all zeros. A plain `std::array<int, 3> u;` leaves ints uninitialized, as a C array would. - Since C++17, class template argument deduction works: `std::array rates{30, 60, 120};` deduces `std::array<int, 3>`. - Since C++20, `std::to_array` builds a `std::array` from a C array or a braced list and deduces both type and size. - `std::array<T, 0>` is allowed, with `begin() == end()`; a C array of size zero is not. ## Details interviewers like to probe - `std::get<0>(a)` and structured bindings such as `auto [x, y, z] = a;` work, because `std::array` provides the tuple-like interface. - `fill(value)` sets every element; there is no constructor taking a size or a fill value, since the size is already in the type. - Passing a large `std::array` by value copies every element; pass it by `const&`, or as a `std::span`, instead. - In C++20 every `std::array` member function is `constexpr`, so a lookup table can be built and checked at compile time. ## When to choose which 1. A small, fixed set known at compile time: emitters, the four corners of a quad, a lookup table. Use `std::array`. 2. A count that changes at run time or is large: use `std::vector`. 3. Interfacing with a C API that takes a pointer and a length: both offer `data()` and `size()`, and both convert to `std::span`. Interviewers asking this question at junior level want the decay point and the copyable value semantics; the move-cost difference from `std::vector` is the follow-up that separates a stronger answer.

  • Why is moving a std::array<std::string, 1000> much more expensive than moving a std::vector<std::string> of the same size?
    A vector owns a heap block, so its move constructor takes over the buffer pointer, size and capacity in constant time. A `std::array` stores its elements inside itself, so there is no buffer to hand over: its implicitly declared move constructor moves each of the 1,000 strings individually. The standard lists move construction and swap as linear for `array` and constant for the other containers.
  • How do you write one function that accepts both std::array<int, 3> and std::array<int, 8>?
    Either make it a template on the size, `template <std::size_t N> void f(const std::array<int, N>&)`, which instantiates once per size, or take a `std::span<const int>` (C++20), which accepts any contiguous range of ints, including both arrays and a `std::vector<int>`, at the cost of a run-time size.

  • std::array allocates its elements on the heap like std::vector
  • A function parameter declared int a[4] still knows it holds four ints
  • std::array has push_back as long as the size limit is not reached
  • Moving a std::array is constant time, just like moving a std::vector
  • operator[] on std::array throws std::out_of_range for a bad index

Assumes C++17 or later; std::to_array and <=> on std::array are C++20, and comparing two built-in arrays with == became ill-formed in C++26.