The Analogy: The Egg Box
A single variable is a cup: one thing in it. An array is an egg box — a run of identical compartments, numbered from zero, all the same size, sitting side by side in memory.
Two consequences follow from "side by side, all the same size". First, the computer can find compartment number 7 instantly: it takes the address of the box and adds seven compartment-widths. No searching. That is why array access is one of the fastest operations there is.
Second, the box does not grow. A six-egg box holds six eggs forever. If you need seven, you need a different box — and if you try to put an egg in slot number six of a six-slot box, you are not putting it in the box at all. You are putting it wherever happens to be next to the box, and C++ will let you.
Syntax or Core Structure
#include <iostream>
#include <array>
int main() {
// Declaration with a fixed, compile-time size
int scores[5]; // uninitialised: five garbage values
int zeroed[5]{}; // all five set to 0
int filled[5]{10, 20, 30, 40, 50}; // explicit values
int partial[5]{10, 20}; // {10, 20, 0, 0, 0} -- rest are zeroed
int inferred[]{1, 2, 3}; // size 3, deduced from the initialiser
// Access is zero-indexed
std::cout << filled[0] << "\n"; // 10 -- the FIRST element
std::cout << filled[4] << "\n"; // 50 -- the LAST element
filled[2] = 99; // assign
// Size in elements: bytes-of-array divided by bytes-of-one-element
const std::size_t count = sizeof(filled) / sizeof(filled[0]);
std::cout << count << "\n"; // 5
// The modern alternative: std::array knows its own size
std::array<int, 5> modern{10, 20, 30, 40, 50};
std::cout << modern.size() << "\n"; // 5
std::cout << modern.at(2) << "\n"; // 30, bounds-checked
std::cout << modern.front() << modern.back() << "\n";
return 0;
}
The size must be a compile-time constant: int a[n]; with a runtime n is not standard C++, even though some compilers allow it. For a size decided at runtime you need std::vector.
Technical Depth: Bounds, Decay and Why std::array Won
There is no bounds checking. None.
int data[3]{1, 2, 3};
std::cout << data[3]; // undefined behaviour -- reads past the end
std::cout << data[-1]; // undefined behaviour -- reads before the start
data[100] = 7; // writes over whatever is 100 ints away. No error.
Python raises IndexError. JavaScript gives undefined. C++ does exactly what you asked: computes the address and reads it. Sometimes you get plausible-looking garbage, sometimes you silently corrupt another variable, sometimes it crashes ten lines later in unrelated code. This is the origin of the buffer-overflow class of security bugs.
Two defences, both cheap: use std::array and call .at() where the index is not obviously safe, and build with the sanitiser during development:
g++ -std=c++20 -fsanitize=address -g -o prog prog.cpp # reports the exact overflow
Arrays decay to pointers when passed to functions
void takesArray(int arr[]) { // this is a LIE -- it is really int*
std::cout << sizeof(arr) << "\n"; // 8 -- the size of a pointer, not the array
// The length information is gone.
}
int main() {
int data[5]{1, 2, 3, 4, 5};
std::cout << sizeof(data) << "\n"; // 20 -- here it still knows
takesArray(data); // passes an address, not a copy
}
A raw array loses its length the moment it crosses a function boundary. That is why C-style code always passes the size alongside it:
double average(const int arr[], std::size_t count) { // size must come too
if (count == 0) return 0.0;
int total{0};
for (std::size_t i = 0; i < count; ++i) { total += arr[i]; }
return static_cast<double>(total) / count;
}
Note also that arrays are not copied when passed — the function receives the address, so writing to arr[0] inside changes the caller's data. Mark it const when you only intend to read.
Arrays cannot be assigned or compared
int a[3]{1, 2, 3};
int b[3];
b = a; // ERROR: cannot assign arrays
if (a == b) { } // compiles, but compares ADDRESSES -- never what you want
std::array<int, 3> x{1, 2, 3};
std::array<int, 3> y = x; // works: a real copy
if (x == y) { } // works: compares CONTENTS
This is the clearest argument for std::array. Same memory layout, same speed, zero overhead — but it behaves like a proper value: copyable, comparable, and it remembers its own size everywhere.
Choosing a container
int a[5] | std::array<int,5> | std::vector<int> | |
|---|---|---|---|
| Size fixed at | compile time | compile time | runtime, and can change |
| Knows its size | only in its own scope | always, .size() | always, .size() |
| Bounds-checked option | no | .at() | .at() |
| Copy / compare | no | yes | yes |
| Where it lives | stack | stack | heap |
| Overhead vs raw array | — | none | one allocation |
| Use it when | interfacing with C | the size is known and fixed | the size varies |
The rule of thumb for modern C++: std::vector by default, std::array when the size is a compile-time constant, raw arrays only when an old API forces it.
Real World Example: Weekly Temperature Log
#include <iostream>
#include <iomanip>
#include <array>
#include <string_view>
int main() {
constexpr std::size_t Days{7};
const std::array<std::string_view, Days> labels{
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
};
std::array<double, Days> temps{18.5, 21.0, 19.4, 23.8, 25.1, 22.0, 17.9};
// Aggregate in one pass
double total{0.0};
double hottest{temps[0]}, coldest{temps[0]};
std::size_t hotIndex{0}, coldIndex{0};
for (std::size_t i = 0; i < temps.size(); ++i) {
total += temps[i];
if (temps[i] > hottest) { hottest = temps[i]; hotIndex = i; }
if (temps[i] < coldest) { coldest = temps[i]; coldIndex = i; }
}
const double mean = total / static_cast<double>(temps.size());
// Report, flagging days above the mean
std::cout << std::fixed << std::setprecision(1);
for (std::size_t i = 0; i < temps.size(); ++i) {
std::cout << labels[i] << " " << std::setw(5) << temps[i] << "C";
if (temps[i] > mean) { std::cout << " (above average)"; }
std::cout << "\n";
}
std::cout << "\nMean: " << mean << "C\n";
std::cout << "Hottest: " << labels[hotIndex] << " at " << hottest << "C\n";
std::cout << "Coldest: " << labels[coldIndex] << " at " << coldest << "C\n";
// Correct a reading -- fixed size, so we overwrite rather than append
temps.at(2) = 20.1;
std::cout << "Wed corrected to " << temps.at(2) << "C\n";
return 0;
}
constexpr std::size_t Days{7} gives one place to change the length, and because it is a compile-time constant it can be the std::array size parameter. Two parallel arrays share an index — a common pattern, and the reason both loops use std::size_t to match .size(). Initialising hottest and coldest from temps[0] rather than from 0.0 matters: a week of freezing temperatures would never beat a zero starting point. The final write uses .at() because the index is a bare literal that a future edit could easily push out of range.
Common Mistakes
- Off-by-one at the end:
for (i = 0; i <= size; ++i)touches one element too many. - Assuming index 1 is the first element. It is index 0, and the last is
size - 1. - Using
sizeof(arr) / sizeof(arr[0])inside a function. After decay,sizeof(arr)is the pointer size, so you get 8/4 = 2 regardless of the real length. - Declaring
int a[n];with a runtimen. Not standard C++; usestd::vector. - Expecting
b = aora == bto work on raw arrays. - Leaving an array uninitialised and reading it.
int a[5]{};costs nothing. - Passing an array and forgetting the size, then guessing it inside the function.
- Returning a local array from a function. It dies at the closing brace; you return a dangling pointer.
Best Practices
- Prefer
std::vector; usestd::arrayfor compile-time-fixed sizes. Reach for raw arrays only at a C boundary. - Always initialise:
int a[5]{};or with explicit values. - Name the size once as a
constexprand use it everywhere instead of repeating the literal. - Loop with
std::size_tand< size(), or better still use a range-basedfor. - Use
.at()when the index came from input,[]inside a loop you have already bounded. - Take
constwhen a function only reads, and always pass the length with a raw array. - Develop with
-fsanitize=address. It turns silent corruption into an immediate, precise error report.
Practice Exercises
- Min, max, mean: Fill a
std::array<int, 10>from user input and report the smallest, largest and average value, plus how many entries were above average. - Reverse in place: Swap the first and last elements, then the second and second-to-last, and so on. Get the stopping condition right for both odd and even lengths.
- Prove the overflow: Write to
data[5]on a five-element array, run the program normally, then rebuild with-fsanitize=addressand record exactly what the sanitiser reports.