C++

C++ Arrays and std::array: C Arrays, Bounds, and the Safe Replacement

An array holds a fixed number of values of one type in a row. This guide runs four programs. The main program declares a C array of three ints and a std::array of three ints, and prints a[0]=1 a[2]=3 size=3, then b.size=3 b[1]=5 b.at(2)=6, then b sum=15. A second program passes the C array to a function and prints inside sizeof=8, because what the function received was a pointer, not the array. A third program asks a std::array for index 5 and catches the std::out_of_range exception that .at() throws. A fourth shows that a partly filled array zero-fills the rest.

Written November 11, 2026 · 6 min read

By the end of this guide
  • The main program: one C array and one std::array
  • The C array: declaration, initialization, and indexing
  • How big is it: the sizeof idiom
  • std::array: the same storage with a type that knows its size

What this guide is

An array stores several values of the same type under one name, and each value is reached by its index. C++ has two array forms. The older form comes from C: you write the element type, the name, and the count in brackets, and the compiler lays the values out in one block of memory. The newer form is std::array, a class template from the standard library that wraps that same block and adds member functions. This guide runs one main program that uses both forms, plus three smaller programs that isolate the traps.

The main program: one C array and one std::array

C++
#include <iostream>
#include <array>
int main() {
    int a[3] = {1, 2, 3};
    std::cout << "a[0]=" << a[0] << " a[2]=" << a[2] << " size=" << sizeof(a)/sizeof(a[0]) << "\n";
    std::array<int, 3> b = {4, 5, 6};
    std::cout << "b.size=" << b.size() << " b[1]=" << b[1] << " b.at(2)=" << b.at(2) << "\n";
    int total = 0;
    for (int v : b) total += v;
    std::cout << "b sum=" << total << "\n";
    return 0;
}

The exact output:

Output
a[0]=1 a[2]=3 size=3
b.size=3 b[1]=5 b.at(2)=6
b sum=15

The first line of main declares the C array. The second declares the std::array. Both hold three int values, and the rest of the program reads them in three different ways: by index, by a member function, and by a range loop that visits each value in turn. The sections below take each form in turn, then the two traps that decide which form to reach for.

The C array: declaration, initialization, and indexing

The declaration int a[3] = {1, 2, 3}; says four things. The element type is int. The name is a. The count is 3, fixed at compile time. The values in braces fill the array in order, so a[0] is 1, a[1] is 2, and a[2] is 3. Indexing starts at 0, so the last valid index of a three-element array is 2, not 3. The main program prints the first and last values to make that visible: a[0]=1 a[2]=3.

The count can be left out when the values are listed, as in int a[] = {1, 2, 3};, because the compiler counts the values. It cannot be left out without a list, because then nothing tells the compiler how much storage to reserve. A partly filled list is allowed, and the remaining elements are set to zero. A fourth program proves that:

C++
#include <iostream>
#include <array>
int main() {
    int a[5] = {1, 2};
    std::cout << "a[0]=" << a[0] << " a[4]=" << a[4] << "\n";
    std::array<int, 3> b{};
    std::cout << "b[0]=" << b[0] << " b[2]=" << b[2] << " empty=" << b.empty() << "\n";
    return 0;
}

The exact output:

Output
a[0]=1 a[4]=0
b[0]=0 b[2]=0 empty=0

The array a was declared with room for five values and given two, so index 4 holds 0. The std::array named b was value-initialized with empty braces, so all three of its values are 0, and .empty() reports 0 because the array is not empty; it holds three zeros. An array with no initializer at all, declared inside a function, is a different case: its elements hold whatever was in that memory, and reading them before writing them is a bug. The brace forms above are the safe habit.

How big is it: the sizeof idiom

A C array does not carry its count with it. The one place the count can be recovered is the scope where the array was declared, using sizeof. The expression sizeof(a) gives the size of the whole array in bytes, and sizeof(a[0]) gives the size of one element, so dividing the first by the second gives the element count. The main program uses exactly that expression and prints size=3. An int is 4 bytes, so sizeof(a) is 12 and the division is 12 over 4.

That idiom works only while a is still an array. It fails silently in the most common place a beginner tries it, inside a function that received the array as a parameter. That failure is the decay trap, and it is next.

Trap: an array passed to a function decays to a pointer

Trap
When an array is passed to a function, the function does not receive the array. It receives a pointer to the first element. Programmers call this decay, and a second program shows what it does to sizeof:
C++
#include <iostream>
void show(int a[]) {
    std::cout << "inside sizeof=" << sizeof(a) << "\n";
}
int main() {
    int a[3] = {1, 2, 3};
    std::cout << "outside sizeof=" << sizeof(a) << " count=" << sizeof(a)/sizeof(a[0]) << "\n";
    show(a);
    return 0;
}

The exact output:

Output
outside sizeof=12 count=3
inside sizeof=8

Outside the function, sizeof(a) is 12, the three ints. Inside, the same expression is 8, the size of a pointer on this 64-bit box. The parameter written as int a[] is a pointer in disguise; the compiler even says so while building the program, warning that sizeof on an array function parameter will return the size of int*, and naming the parameter type as int* in its own message. A function that needs to know how many elements it was handed must be told, so C-style code passes the count as a second argument. Indexing still works inside the function, because a pointer can be indexed, which is why the bug hides: the values read correctly while the count is wrong.

Key result
the same sizeof expression prints 12 outside the function and 8 inside it. A parameter declared int a[] is a pointer to the first element, so the count is lost at the call and must be passed separately.

std::array: the same storage with a type that knows its size

std::array is a class template in the <array> header. The declaration std::array<int, 3> b = {4, 5, 6}; states the element type and the count as template arguments, and the values follow in braces, exactly as with the C array. The storage is the same fixed block; what changes is the interface around it. The object knows its count, so b.size() returns 3 without any sizeof arithmetic. It can be ranged over, as the main program does when it adds the values and prints b sum=15. It can be copied and returned from a function as a whole value, which a C array cannot. And it does not decay: passing a std::array to a function passes the object, with its size still attached, and a function can also take it by reference when a copy is not wanted.

The count is part of the type. A std::array<int, 3> and a std::array<int, 4> are different types, and the count must be known at compile time, just as with the C form. Code that needs a count chosen at run time uses std::vector instead; the containers guide on this site covers it alongside map and set.

Bounds: operator[] does not check, .at() does

Both forms read an element with the bracket operator, as in b[1], which printed 5 in the main program. The bracket operator performs no bounds checking on either form. Asking for an index outside the array is undefined behavior: the program may read unrelated memory, print a plausible wrong value, or crash, and none of those outcomes is guaranteed. There is no error message to quote for it, because the language promises none.

std::array offers a second access form that does check. The member function .at() compares the index with the size and throws an exception of type std::out_of_range when the index is too large. The main program used it in range, printing b.at(2)=6. A third program uses it out of range and catches the throw:

C++
#include <iostream>
#include <array>
#include <stdexcept>
int main() {
    std::array<int, 3> b = {4, 5, 6};
    try {
        std::cout << b.at(5) << "\n";
    } catch (const std::out_of_range& e) {
        std::cout << "caught out_of_range: " << e.what() << "\n";
    }
    std::cout << "after catch b[2]=" << b[2] << "\n";
    return 0;
}

The exact output:

Output
caught out_of_range: array::at: __n (which is 5) >= _Nm (which is 3)
after catch b[2]=6

The exception message names the index asked for, 5, and the size it was checked against, 3. The wording of that message comes from this standard library implementation, so another compiler may phrase it differently; the type of the exception, std::out_of_range, is the part the language guarantees. The program survived the bad access and went on to print b[2]=6, which is the practical difference: a checked access fails in a way the program can handle, while an unchecked one fails in a way it cannot predict. The check costs a comparison per access, so code that has already proven its indices in range often uses the bracket operator in the hot path and .at() where an index comes from outside the program, such as user input or a file.

Trap: the last index is the size minus one

Trap
Most array bugs are off by one. A three-element array has indices 0, 1, and 2. A loop written as for (int i = 0; i <= 3; i++) runs one step too many and reads index 3, which does not exist. The standard loop forms avoid the trap by testing with < against the size, as in i < 3 or i < b.size(), or by using a range loop that never names an index at all, as the main program does when it sums b. When an index is computed rather than counted, for example read from input or derived from other data, that is the case .at() exists for.

Which form for which job

Job Form Why
A fixed set of values created and used in one scope C array, as in int a[3] The declaration is one line and the sizeof idiom still works in that scope
A fixed set of values passed to functions std::array, as in std::array<int, 3> b The size travels with the object; no separate count argument and no decay
An index that comes from outside the program std::array read with .at() An out-of-range index throws std::out_of_range instead of reading unrelated memory
A count only known at run time Neither; use std::vector Both array forms fix the count at compile time, as part of the declaration or the type
Interfacing with a C library that takes a pointer and a count C array, or .data() on a std::array The library wants the first element's address; .data() returns exactly that pointer

The deciding question is whether the size needs to travel. Inside one scope the C array is enough. The moment the values cross a function boundary, the form that carries its own size is the safer default.

Checklist

  • Before indexing an array, check that the index is at least 0 and at most the size minus one. The last valid index of a three-element array is 2.
  • Before using the sizeof division idiom, check that the array was declared in the current scope. Inside a function that received it, the same expression measures a pointer.
  • Before passing a C array to a function that needs the count, add a count parameter. The function cannot recover the count on its own.
  • Before reading an element at an index that came from input or a calculation, use .at() on a std::array, or check the index against the size yourself.
  • Before leaving elements uninitialized, give the array a brace initializer. A short list zero-fills the rest; no list leaves whatever was in memory.
  • Before choosing the form, decide whether the count is fixed at compile time. If it is not, neither array form fits; use std::vector.

Sources

  • cppreference, Array declaration — the declaration form, the fixed count, and how an array converts to a pointer to its first element.
  • cppreference, std::array — the class template, its fixed size as part of the type, and its member functions including size, empty, and data.
  • cppreference, std::array::at — the checked access form and the std::out_of_range exception it throws.
  • Structure reference only: the learncpp introduction to C-style arrays, read for how the topic is usually sequenced; no figure or wording in this guide comes from it.

Keep Exploring