TExcelTAD
Home › C++ › C++ Arrays

C++ Arrays

An array stores a fixed number of values of the same type, one after another in memory. Instead of declaring score1, score2, score3… you declare one array and access its elements by index.

Creating an array

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

int main() {
    string fruits[3] = {"apple", "banana", "cherry"};
    int temps[] = {18, 21, 19, 24, 22};   // size deduced: 5

    cout << fruits[0] << "\n";
    cout << temps[3] << "\n";

    fruits[1] = "blueberry";   // change an element
    cout << fruits[1] << "\n";
}
apple
24
blueberry
  • Indexes start at 0, so the last element of a 5-element array is at index 4.
  • The size must be a compile-time constant and can never change.
  • If you give fewer initialisers than the size, the rest are zero: int a[5] = {1, 2}; gives {1, 2, 0, 0, 0}.

Warning: C++ does not check array bounds. Reading temps[10] compiles fine but is undefined behaviour — it may print garbage or crash. Always keep indexes in range.

Looping over an array

Use a classic for loop when you need the index, or a range-based loop when you just need the values. std::size (C++17) gives the number of elements:

cpp · try it yourself
#include <iostream>
using namespace std;

int main() {
    int temps[] = {18, 21, 19, 24, 22};

    for (size_t i = 0; i < size(temps); i++) {
        cout << "Day " << i + 1 << ": " << temps[i] << "\n";
    }

    int total = 0, highest = temps[0];
    for (int t : temps) {
        total += t;
        if (t > highest) highest = t;
    }
    cout << "Average: " << static_cast<double>(total) / size(temps) << "\n";
    cout << "Highest: " << highest << "\n";
}
Day 1: 18
Day 2: 21
Day 3: 19
Day 4: 24
Day 5: 22
Average: 20.8
Highest: 24

In older code you will see sizeof(temps) / sizeof(temps[0]) to compute the element count — it does the same thing.

Multi-dimensional arrays

An array of arrays forms a grid. The first index selects the row, the second the column:

cpp · try it yourself
#include <iostream>
using namespace std;

int main() {
    char board[3][3] = {
        {'X', 'O', 'X'},
        {' ', 'X', 'O'},
        {'O', ' ', 'X'}
    };

    for (int r = 0; r < 3; r++) {
        for (int c = 0; c < 3; c++) {
            cout << board[r][c];
            if (c < 2) cout << '|';
        }
        cout << "\n";
    }
    cout << "Center: " << board[1][1] << "\n";
}
X|O|X
 |X|O
O| |X
Center: X

std::array: the safer modern array

The <array> header provides std::array<T, N>, a thin wrapper around a built-in array. It has the same speed but knows its size, can be copied and compared, and offers bounds-checked at():

cpp · try it yourself
#include <iostream>
#include <array>
#include <algorithm>
using namespace std;

int main() {
    array<int, 5> nums = {42, 7, 19, 3, 25};
    sort(nums.begin(), nums.end());

    for (int n : nums) cout << n << " ";
    cout << "\nsize: " << nums.size() << "\n";
    cout << "front: " << nums.front() << ", back: " << nums.back() << "\n";

    array<int, 5> copy = nums;      // built-in arrays cannot be copied like this
    cout << boolalpha << (copy == nums) << "\n";
}
3 7 19 25 42
size: 5
front: 3, back: 42
true

Tip: Need an array whose size can change at runtime? Use std::vector, covered in the STL section. In modern C++, std::array and std::vector are preferred over raw arrays.

Test yourself

What is the index of the last element in int a[8]?

  1. 8
  2. 7
  3. 9
  4. 0

What does int a[4] = {5}; contain?

  1. {5, 5, 5, 5}
  2. {5, 0, 0, 0}
  3. {5, garbage...}
  4. Compile error

What happens when you read a[10] from a 5-element built-in array?

  1. An exception is thrown
  2. It returns 0
  3. Undefined behaviour
  4. Compile error