std::array
std::array<T, N> is a fixed-size sequence of N elements of type T. It wraps a C array with iterators, size(), and value semantics, and it stores the elements inline: no heap allocation.
Detailed Explanation
A C array int xs[4]; decays to a pointer the moment you pass it to a function, loses its length, and cannot be returned by value without wrapping it in a struct. std::array<int, 4> is that struct, written once in the standard library. sizeof(std::array<int, 4>) is 4 * sizeof(int) plus no extra words. The elements sit inside the object, so a local array lives on the stack.
N is a compile-time constant. You cannot push_back. You cannot grow. If you need a length that changes, use std::vector. If you need a view of existing memory, use std::span. If you need a C array to talk to a C API, data() returns T* and is the right seam.
Value semantics work. auto b = a; copies every element. a == b compares elementwise. You can return an array from a function. You can store one in another container. You can std::sort(a.begin(), a.end()).
at(i) throws std::out_of_range on a bad index. operator[] does not check. front, back, data, empty, size, max_size (equal to N), fill, and swap complete the container surface. Iterators are ordinary pointers on every mainstream library, so an array is a contiguous range.
C++17 class template argument deduction lets you write std::array a{1, 2, 3}; and get std::array<int, 3>. std::to_array (C++20) converts a C array or an initializer list to a std::array and can deduce the type and count.
constexpr support is complete in modern libraries: you can build and read an array at compile time. That makes it the default table type for lookup data you used to write as a file-scope C array.
std::array<T, 0> is a valid empty array. data() may return nullptr or a valid pointer you must not dereference; do not assume which.
Compared with std::vector of a known size: vector still allocates, still stores a pointer, size, and capacity, and still lets you grow. Use array when N is part of the type (mat4 as array<float, 16>, an IPv4 address as array<uint8_t, 4>). Use vector plus reserve when N is large or known only at runtime.
Code Examples
#include <algorithm>
#include <array>
#include <iostream>
int main() {
std::array<int, 4> scores{9, 3, 7, 1};
std::sort(scores.begin(), scores.end());
for (int n : scores) std::cout << n << ' ';
std::cout << '\n'; // prints: 1 3 7 9
std::cout << scores.size() << '\n'; // prints: 4
}#include <array>
#include <cstdint>
std::array<std::uint8_t, 4> localhost() {
return {127, 0, 0, 1}; // return by value; no decay
}
int main() {
auto ip = localhost();
(void)ip[0];
}Common Gotchas
`operator[]` is unchecked
`a[4]` on a 4-element array is undefined behaviour. Use `at` when the index came from input.
`N` is part of the type
`array<int, 3>` and `array<int, 4>` cannot go in the same `vector` without a wrapper. Use `vector` or `span` when the length varies.