C++ Arrays and std::array

An array keeps many values of the same type in a row. The size is fixed, and the index starts at 0.

C style array

#include <iostream>

int main() {
    int marks[4] = {70, 85, 90, 65};
    marks[1] = 88;
    std::cout << marks[0] << ' ' << marks[1] << '\n';
    std::cout << "bytes: " << sizeof(marks) << ", items: " << sizeof(marks) / sizeof(marks[0]) << '\n';

    int total = 0;
    for (int m : marks) total += m;
    std::cout << "Total: " << total << '\n';
}
Output

70 88
bytes: 16, items: 4
Total: 313

std::array: the better array

std::array (in <array>) has a fixed size, but it knows its size and has helper functions.

#include <algorithm>
#include <array>
#include <iostream>

int main() {
    std::array<int, 5> n = {5, 2, 9, 1, 7};
    std::cout << n.size() << ' ' << n.front() << ' ' << n.back() << ' ' << n.at(2) << '\n';

    std::sort(n.begin(), n.end());
    for (int x : n) std::cout << x << ' ';
    std::cout << '\n';

    std::array<int, 3> zeros{};            // all zero
    std::cout << zeros[0] + zeros[1] + zeros[2] << '\n';
}
Output

5 5 7 9
1 2 5 7 9
0

Arrays decay to pointers

When a C array is passed to a function, it becomes a pointer, and the size is lost. std::array keeps its size.

#include <array>
#include <iostream>

void c_style(int arr[]) {                           // really: int* arr
    std::cout << "inside a function: " << sizeof(arr) << " bytes (a pointer)\n";
}

int main() {
    int a[10] = {};
    std::cout << "in main: " << sizeof(a) << " bytes\n";
    c_style(a);
}
Output

in main: 40 bytes
inside a function: 8 bytes (a pointer)

Two dimensions

#include <array>
#include <iostream>

int main() {
    std::array<std::array<int, 3>, 2> m = {{{1, 2, 3}, {4, 5, 6}}};
    for (const auto& row : m) {
        for (int v : row) std::cout << v << ' ';
        std::cout << '\n';
    }
}
Output

1 2 3
4 5 6

Going outside the array

In C++, [] does not check the index. A wrong index is undefined behavior: the program may crash or give a wrong value. at() checks and throws an exception:

#include <array>
#include <iostream>

int main() {
    std::array<int, 3> a = {1, 2, 3};
    try {
        std::cout << a.at(5) << '\n';
    } catch (const std::out_of_range& e) {
        std::cout << "Caught: " << e.what() << '\n';
    }
}
Output

Caught: array::at: __n (which is 5) >= _Nm (which is 3)

Note: Use std::array for a fixed size and std::vector when the size can change. Next: C++ Vectors.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.