Skip to content

Beginner · References, pointers, arrays and strings · topic 11 of 42 · 30 min

Arrays, std::array and a first look at std::vector

Explanation

An array stores many values of one type side by side, accessed by index from 0. C-style arrays have a fixed size and no bounds checks; std::array is the safer fixed-size version; std::vector can grow and is the default choice for lists in modern C++.

Why arrays?

Storing the marks of 60 students in 60 separate variables is impossible to manage. An array is one variable that holds many values of the same type in a row, next to each other in memory. Each value is an element, and you reach it by its index: its position, starting from 0.

Think of it like this: An array is like a row of lockers at a railway station, numbered from 0. All lockers are the same size (same type), they stand side by side, and you open one by its number. Asking for locker 60 in a row of 60 (numbered 0 to 59) opens someone else's property.

C-style arrays

cpp
int marks[5] = {78, 91, 64, 85, 70};
std::cout << marks[0] << '\n';   // 78, the first element
marks[4] = 72;                    // change the last one (index 4, not 5)

int scores[3] = {};               // all three are 0
const int N = 4;
double prices[N] = {10.5, 20.0};  // the rest become 0.0
The size must be a constant known at compile time. Indexes run from 0 to size - 1.
Careful: C++ does NOT check array indexes. marks[5] on a 5-element array reads or writes memory that is not yours: undefined behaviour. It may print garbage, crash, or silently corrupt another variable. This is the classic "buffer overflow" behind many security bugs.

C-style arrays also forget their size when passed to a function: they "decay" into a pointer to the first element. That is why C functions take the size as a separate parameter.

std::array: a fixed array that knows its size

cpp
#include <array>

std::array<int, 5> marks = {78, 91, 64, 85, 70};
std::cout << marks.size() << '\n';   // 5
std::cout << marks.at(2) << '\n';    // 64, with bounds checking
// marks.at(9) throws std::out_of_range instead of corrupting memory
std::array<type, size> has the same speed as a C array but knows its size, can be copied and works with the standard algorithms.

std::vector: an array that grows

cpp
#include <vector>

std::vector<int> orders;          // empty
orders.push_back(450);            // add at the end
orders.push_back(1200);
orders.push_back(99);
std::cout << orders.size() << '\n';   // 3
std::cout << orders[1] << '\n';       // 1200

std::vector<int> zeros(10, 0);        // 10 elements, all 0
for (int o : orders) std::cout << o << ' ';
Use std::vector whenever the number of items is known only at run time. You will learn its internals in the STL module.

2D arrays: rows and columns

cpp
int seats[3][4] = {};                     // 3 rows, 4 columns, all 0
seats[1][2] = 1;                             // book row 1, column 2

std::vector<std::vector<char>> grid(3, std::vector<char>(4, '.'));
grid[0][3] = '#';
for (const auto& row : grid) {
    for (char c : row) std::cout << c;
    std::cout << '\n';
}
A vector of vectors is the usual way to make a grid whose size is known at run time.

Which one should I use?

NeedUse
A list whose size changes or is read from inputstd::vector<T>
A small list whose size is fixed at compile timestd::array<T, N>
Talking to C code or very old codeC-style array

Common mistakes

  • Using <= size in a loop: for (int i = 0; i <= 5; ++i) on a 5-element array goes one past the end.
  • Using sizeof(arr) inside a function to get the length: it gives the size of a pointer there.
  • Indexing an empty vector: v[0] on an empty vector is undefined behaviour. Check v.empty() first, or use v.at(0), which throws an exception.
Tip: While learning, compile with -D_GLIBCXX_ASSERTIONS (GCC's libstdc++) to make vector's [] check bounds, or use .at() so mistakes stop the program with a clear error.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Arrays, std::array and a first look at std::vector · 1/6

Arrays

An array keeps many values of one type in a row, reached by an index that starts at zero.

Prefer a video by a teacher? Find free videos on “c++ arrays std::array std::vector tutorial beginners” on YouTube ↗

In real life: Cinema seat booking

A multiplex app shows a grid of seats: rows A to J and numbered columns. The program stores the hall as a 2D grid of characters, marks booked seats, and counts free seats in a row before you pay.

cpp
#include <iostream>
#include <vector>

int main() {
    int rows = 3, cols = 6;
    std::vector<std::vector<char>> hall(rows, std::vector<char>(cols, 'O'));
    hall[1][2] = 'X';
    hall[1][3] = 'X';
    int freeInRowB = 0;
    for (char seat : hall[1]) {
        if (seat == 'O') ++freeInRowB;
    }
    std::cout << "Free seats in row B: " << freeInRowB << '\n';   // 4
}
Row index 1 is row B. O is free, X is booked.

Practice (0/4 done)

Task 1 · Question

int a[4] = {5, 10, 15, 20}; What is a[3]?

Task 2 · Question

What does this print? std::vector<int> v = {3, 1, 4}; v.push_back(1); v.push_back(5); std::cout << v.size() << " " << v[3];

Task 3 · Question

int m[3] = {1, 2, 3}; std::cout << m[3]; What happens?

Task 4 · Practice

Read n, then n daily temperatures into a std::vector<int>. Print the average, the highest and the lowest temperature, and how many days were above the average.

Quick quiz

Question 1

1.What is the index of the LAST element of an array of size 10?

Question 2

2.What is the main advantage of std::vector over a C-style array?

Question 3

3.What does v.at(10) do on a vector of size 3?

Question 4

4.int a[5] = {1, 2}; What are a[2], a[3] and a[4]?

Question 5

5.Why do C functions that take an array also take its size?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is the index of the LAST element of an array of size 10?

Answer: 9

Indexes run from 0 to size - 1.

What is the main advantage of std::vector over a C-style array?

Answer: Its size can change at run time and it knows its size

vector grows with push_back and reports size(); it also manages its own memory.

What does v.at(10) do on a vector of size 3?

Answer: Throws std::out_of_range

.at() checks the index and throws an exception; [] does not check.

int a[5] = {1, 2}; What are a[2], a[3] and a[4]?

Answer: 0, 0, 0

When an initialiser list is shorter than the array, the remaining elements are zero-initialised.

Why do C functions that take an array also take its size?

Answer: Because a C array passed to a function decays into a pointer and loses its size

Inside the function the array is just a pointer to the first element.

What does std::remove(v.begin(), v.end(), 0) do on its own?Related

Answer: Moves non-zero elements to the front and returns the new logical end; the size is unchanged

You must call erase with the returned iterator to actually shrink the vector.

From std::vector in depth

What is the index of the last item in an array of length 8?Related

Answer: 7

Indexes go from 0 to Length - 1.

From Arrays: one name, many values

std::string a = "apple", b = "Apple"; Is a == b?Related

Answer: No, comparison is case sensitive

Characters are compared exactly; 'a' and 'A' are different.

From Text: C strings and std::string

How many frees does an array of 5 row pointers (each row malloc'd) need?Related

Answer: 6

5 rows + the pointer array.

From Dynamic strings and 2D arrays

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “References, pointers, arrays and strings” before its exam: Text: C strings and std::string.
  2. Module 3 exam: References, pointers, arrays and strings · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Classes, constructors and RAII. 42 topics left in the course before the final exam.

← Previous: Pointers, the stack and the heap