Thuta Learning
C++
IntermediateProgrammingBeginner

Arrays

C++Lesson 1325 min

What you'll walk away with

  • Declare a std::array, read and write elements by index, and loop over it with a range-based for
  • Explain why the last valid index is size() - 1 and what happens past it with [] versus .at()
  • Choose between a C array, std::array and std::vector for a given job
  • Write functions that take std::span<const T> so they accept arrays and vectors alike

Explain it simply

Explain it simply

An array is a row of numbered boxes that sit side by side in memory, all holding the same type. A pill organizer with seven compartments is a good picture: the number of compartments is decided when it is made, and each one is labelled, Monday to Sunday. In C++ the labels are numbers that start at 0, so a three-box array has boxes 0, 1 and 2.

Modern C++ gives you three tools for this job. std::array<T, N> is the fixed row of N boxes. std::vector<T> is a row that can grow while the program runs. The old C-style array, written int marks[5], still exists, but it forgets its own size too easily, so new code prefers the first two.

Problem → Why → Solution

The problem: arrays that run past their end or forget their size

Below is a C-style array of five marks and two helpers. printAll() loops with i <= 5, one step too far, so the last iteration reads marks[5], a box that does not exist. countMarks() tries the classic sizeof trick to count the elements, but it prints 2 on a typical 64-bit build instead of 5. Neither bug stops the build; the compiler only warns about the second one.

marks.cpp
#include <iostream>

void printAll(int marks[]) {
    for (int i = 0; i <= 5; i++) {          // one step too far
        std::cout << marks[i] << '\n';      // marks[5] does not exist
    }
}

int countMarks(int marks[]) {
    return sizeof(marks) / sizeof(marks[0]); // size of a pointer!
}

int main() {
    int marks[5] = {70, 82, 64, 91, 58};
    printAll(marks);
    std::cout << "count: " << countMarks(marks) << '\n';  // 2, not 5
}

Why does C++ let this happen?

The [] operator on a C array does no bounds check at all: reading past the end is undefined behaviour, so the program may print garbage, crash, or seem fine until the day it is not. And when a C array is passed to a function it decays to a pointer to its first element, so the length is lost; that is why GCC warns 'sizeof' on array function parameter 'marks' will return size of 'int*'. std::array keeps its size in its type, std::vector stores it at runtime, and .at() checks every index.

Core concept: one row in memory

An array is one contiguous block of memory holding N elements of the same type. Because every element has the same size, the address of element i is simply the start of the block plus i times that size. That is why indexing is instant no matter how long the array is, and also why indexes start at 0: element 0 sits at offset zero. The last valid index is always size() - 1.

text
std::array<int, 4> marks{70, 82, 64, 91};
-----------------------------------------
 index:    [0]    [1]    [2]    [3]
         +------+------+------+------+
 marks   |  70  |  82  |  64  |  91  |   one block, no gaps
         +------+------+------+------+
 offset:   0      4      8      12       bytes (int is 4 bytes here)

 marks[4] would be the box after the last one: it does not exist.

std::array<T, N> wraps that block in a proper type. N is part of the type, so std::array<int, 4> and std::array<int, 5> are different types, and the size can never be lost: marks.size() works anywhere, even inside a function. It can be copied and compared with ==, and it does not decay into a pointer. In practice it has the same size and speed as a C array.

Reading an element has two spellings. marks[i] trusts you completely: if i is out of range, behaviour is undefined and nothing reports it. marks.at(i) checks the index first and throws std::out_of_range when it is wrong, which you can catch and handle. Use .at() whenever the index comes from outside the program, such as user input or a file, and [] inside loops whose bounds already guarantee a valid index.

When the number of elements is not known until the program runs, use std::vector<T> instead: it keeps the same contiguous layout but can grow with push_back(). Both containers also work with the range-based for loop, for (const auto& x : marks), which visits each element exactly once and cannot run off the end.

ToolSizeUse it when
C array (int a[5])fixed, lost when passed to a functiontalking to old C APIs
std::array<int, 5>fixed, part of the typethe count is known when you write the code
std::vector<int>grows at runtimethe count depends on input
Mental model: numbered boxes in one row
  1. N boxes of one type, side by side
  2. Index i = start + i * element size
  3. Valid indexes run from 0 to size() - 1
  4. [] trusts you; .at() checks and throws

If an index could ever be wrong, let .at() check it; if a loop already guarantees it, [] is fine.

General pattern

cpp
std::array<Type, N> name{value0, value1, value2};  // fixed size N
std::vector<Type> list{value0, value1};            // can grow

name[index] = newValue;     // no bounds check
name.at(index);             // throws std::out_of_range if index >= size()
name.size();                // number of elements
list.push_back(value);      // vector only: add at the end

for (const Type& item : name) {
    // read each element once
}

N must be a compile-time constant, and every value must have type Type. Both [] and .at() return a reference to the element, so you can read or assign through either. push_back() exists only on vector, because a std::array cannot change its size.

Example: a course list in a std::array

The program stores three course names, reads the first one, replaces the third, and prints them all. The last step asks for a fourth course with .at(3) to show what a checked access does when the index is out of range.

courses.cpp
#include <array>
#include <iostream>
#include <stdexcept>
#include <string>

int main() {
    std::array<std::string, 3> courses{"HTML", "CSS", "C++"};

    std::cout << "First: " << courses[0] << '\n';
    courses[2] = "JavaScript";

    for (const std::string& course : courses) {
        std::cout << "- " << course << '\n';
    }
    std::cout << "Count: " << courses.size() << '\n';

    try {
        std::cout << courses.at(3) << '\n';
    } catch (const std::out_of_range&) {
        std::cout << "courses.at(3) is out of range\n";
    }
}

Code breakdown

  1. Line 7std::array<std::string, 3> courses{"HTML", "CSS", "C++"};

    The type says three std::string elements. The braces fill indexes 0, 1 and 2 in order; any element left out would be default-constructed as an empty string.

  2. Line 10courses[2] = "JavaScript";

    [] returns a reference to the element, so assigning to it replaces "C++" in place. Index 2 is the third and last valid box.

  3. Line 12for (const std::string& course : courses) {

    The range-based for visits every element once. const std::string& reads each name without copying it.

  4. Line 15courses.size()

    size() comes from the type itself, so it is always 3 here, and it stays correct even after the array is passed to a function.

  5. Lines 17-21courses.at(3)

    Index 3 is one past the end. .at() notices, throws std::out_of_range, and the catch block prints a message instead of the program reading memory that does not belong to the array.

You should see
First: HTML
- HTML
- CSS
- JavaScript
Count: 3
courses.at(3) is out of range

std::vector: when the count is not known in advance

A sign-up list cannot be a std::array, because you do not know how many people will join. std::vector<T> keeps its elements in one contiguous block just like an array, but it owns that block on the heap and moves to a bigger one when push_back() runs out of room. You get size(), [], .at() and range-for exactly as before, plus back() for the last element.

signups.cpp
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> signups;
    signups.push_back("Aye");
    signups.push_back("Bo");
    signups.push_back("Chit");

    std::cout << "Signed up: " << signups.size() << '\n';
    std::cout << "Last: " << signups.back() << '\n';
}

Growing can move the elements

When a vector grows it may move every element to a new block. Pointers or references to elements taken before the push_back() can then refer to freed memory, so re-read elements by index after adding to a vector.

std::span: one function for every kind of array

Before C++20, a function that averaged marks had to pick one container type, or take a pointer plus a separate length. std::span<const T> from <span> is a lightweight view: a pointer and a size bundled together. It owns nothing and copies nothing, and it converts automatically from a std::array, a std::vector or a C array, so one function serves them all. first(n) and last(n) give a smaller view of the same elements.

average.cpp
#include <array>
#include <format>
#include <iostream>
#include <span>
#include <vector>

double average(std::span<const int> marks) {
    if (marks.empty()) return 0.0;
    int sum = 0;
    for (int mark : marks) sum += mark;
    return static_cast<double>(sum) / marks.size();
}

int main() {
    std::array<int, 3> quiz{70, 80, 90};
    std::vector<int> exams{55, 65};
    int legacy[4] = {100, 90, 80, 70};

    std::cout << std::format("{:.1f}\n", average(quiz));                    // 80.0
    std::cout << std::format("{:.1f}\n", average(exams));                   // 60.0
    std::cout << std::format("{:.1f}\n", average(legacy));                  // 85.0
    std::cout << std::format("{:.1f}\n", average(std::span(legacy).first(2))); // 95.0
}

Because a span is only a view, it is valid only while the container it looks at is alive and has not reallocated. Using it as a function parameter, for the length of one call, is the safest way to use it.

In real projects

Where this shows up in real projects

Fixed-size arrays show up wherever the count is part of the problem itself: the 7 days of a week, the 12 months of a sales report, the 3 colour channels of a pixel, the 64 squares of a chess board. Game and graphics code uses std::array for small vectors and matrices, such as std::array<float, 3> for a position, because the size is known and the data stays in one compact block that the CPU can read quickly.

Most other lists, such as rows loaded from a file, items in a shopping cart or messages from a server, are std::vector, the default container in C++ code. Library functions increasingly take std::span so callers can pass whichever container they have. In safety-minded teams, code reviews look for .at() or an explicit range check wherever an index comes from user input.

Common mistakes

Common mistakes

1. Looping with <= size

for (int i = 0; i <= 3; i++) on a three-element array runs four times and reads courses[3], which is past the end. This is undefined behaviour, not an exception, so it may even appear to work. Loop with i < courses.size(), or better, use a range-based for that cannot overrun.

2. Expecting [] to throw

Wrapping courses[i] in try/catch catches nothing: [] never throws, however wild the index. Only .at() reports a bad index with std::out_of_range. If you need the check, call .at(), or compare the index with size() yourself.

3. Counting a parameter's elements with sizeof

Inside void f(int marks[]), marks is really an int*, so sizeof(marks) / sizeof(marks[0]) gives 2 on a typical 64-bit build whatever the real length is. Take a std::span<const int> or a const std::array<int, N>& instead, and ask for .size().

4. Printing before the checked access

In std::cout << "Day " << d << ": " << temps.at(d);, the text "Day 7: " is already printed before temps.at(d) throws, leaving half a line on screen. Read the element into a variable first, then print it.

Best practices

Best practices

  • Default to std::vector; reach for std::array when the count is a fixed fact of the problem.
  • Prefer range-based for loops, which cannot index past the end.
  • Use .at() for indexes that come from input, and [] in loops whose bounds you control.
  • Take std::span<const T> in functions that only read a sequence.

Mini challenge

Mini challenge: a week of temperatures

Store a week of daily temperatures and the day names in two std::array objects, then report the hottest day, the averages and a checked lookup.

  • Write int hottestIndex(std::span<const int> temps) that returns the index of the largest value
  • Write double average(std::span<const int> temps) that returns 0.0 for an empty span
  • Print the weekly average and the weekend average (the last two days) with one decimal
  • Look up day 2 and day 7 with .at() and print "no such day" for the bad index
temperatures.cpp
#include <array>
#include <format>
#include <iostream>
#include <span>
#include <stdexcept>
#include <string>

int hottestIndex(std::span<const int> temps) {
    // TODO: remember the index of the largest value seen so far
}

double average(std::span<const int> temps) {
    // TODO: 0.0 for an empty span, otherwise sum / size
}

int main() {
    // TODO: a std::array of 7 day names (Mon..Sun) and one of 7 temperatures:
    //       31, 33, 36, 34, 30, 29, 32
    // TODO: print the hottest day, the week average and the weekend average
    // TODO: look up day 2 and day 7 with .at() inside try/catch
}

Expected: The program should print these five lines: Hottest: Wed (36 C) Week average: 32.1 C Weekend average: 30.5 C Day 2: 36 C Day 7: no such day

Show hint

Start best at 0 and compare from index 1. std::span(temps).last(2) gives a view of the final two elements. Read temps.at(day) into a variable before printing, so a bad index does not leave half a line on screen.

Show solution
temperatures.cpp
#include <array>
#include <format>
#include <iostream>
#include <span>
#include <stdexcept>
#include <string>

int hottestIndex(std::span<const int> temps) {
    int best = 0;
    for (int i = 1; i < static_cast<int>(temps.size()); ++i) {
        if (temps[i] > temps[best]) best = i;
    }
    return best;
}

double average(std::span<const int> temps) {
    if (temps.empty()) return 0.0;
    int sum = 0;
    for (int t : temps) sum += t;
    return static_cast<double>(sum) / temps.size();
}

int main() {
    const std::array<std::string, 7> days{"Mon", "Tue", "Wed", "Thu",
                                          "Fri", "Sat", "Sun"};
    const std::array<int, 7> temps{31, 33, 36, 34, 30, 29, 32};

    int hot = hottestIndex(temps);
    std::cout << "Hottest: " << days[hot] << " (" << temps[hot] << " C)\n";
    std::cout << std::format("Week average: {:.1f} C\n", average(temps));
    std::cout << std::format("Weekend average: {:.1f} C\n",
                             average(std::span(temps).last(2)));

    for (int day : {2, 7}) {
        try {
            int value = temps.at(day);
            std::cout << "Day " << day << ": " << value << " C\n";
        } catch (const std::out_of_range&) {
            std::cout << "Day " << day << ": no such day\n";
        }
    }
}

Quick quiz 1 / 3

Given std::array<int, 4> scores{};, which expression reads the last element?

Quick quiz 2 / 3

What does std::array<int, 3> a{1, 2, 3}; try { a[5] = 9; std::cout << "ok"; } catch (const std::out_of_range&) { std::cout << "caught"; } do?

Quick quiz 3 / 3

Which parameter lets one function read a std::array<int, 7>, a std::vector<int> and an int[10] without copying?

What to remember

  • An array is N same-typed elements in one contiguous block; valid indexes are 0 to size() - 1.
  • std::array<T, N> knows its size and does not decay to a pointer; std::vector<T> grows at runtime.
  • [] does no checking (out of range is undefined behaviour); .at() throws std::out_of_range.
  • std::span<const T> lets one function read any contiguous sequence without copying it.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Arrays | Thuta Learning