The short answer
In C++, you define an array by giving its element type, a name and a size. You can use a C-style array, such as int numbers[5];, or an std::array from the <array> header, such as std::array<int, 5> numbers;.
C-style arrays
int scores[5]; // 5 ints, not set when declared inside a function
int primes[5] = {2, 3, 5, 7, 11};
int counts[] = {1, 1, 2, 3}; // the size is 4, taken from the list
int zeros[5] = {}; // all five are 0
The size of a C-style array must be a constant in standard C++. Writing int n = 5; int a[n]; is not standard C++, although some compilers accept it as an extension.
Indexes start at 0, so primes[0] is 2 and primes[4] is 11. To count the elements of a C-style array in the same scope, divide its total size by the size of one element:
int count = sizeof(primes) / sizeof(primes[0]); // 5
Since C++17, std::size(primes) from <iterator> gives the same result.
std::array
#include <array>
std::array<int, 5> scores{}; // all five are 0
std::array<int, 5> primes{2, 3, 5, 7, 11};
std::array counts{1, 1, 2, 3}; // C++17: the size 4 is deduced
The element type and the size go in angle brackets. Since C++17, you can leave them out when the braces list values of one type, and the compiler works them out.
The size is part of an std::array’s type, so std::array<int, 5> and std::array<int, 4> are different types.
Which one to use
Many C++ programmers prefer std::array for fixed-size data. It knows its own size, can be copied with =, and can be checked with at(). C-style arrays still appear in older code and in C libraries, so it helps to read them too.
For how to hand one of these to a function, see how to pass an array to a function in c. For returning one, see how to return an array in c. A longer walkthrough of the std::array type is in c std::array.
Common mistakes
- Using an ordinary variable as the size of a C-style array.
- Forgetting that indexes start at 0. For five elements, the last valid index is 4, so
primes[5]is out of range. - Leaving a local array uninitialized and reading its values before assigning them.
- Forgetting
#include <array>when you usestd::array.