The short definition
An array is an ordered collection of elements that all have the same type. The elements are stored one after another in memory, and each one is reached by its index. In C and C++, a built-in array has a fixed number of elements, set when you declare it.
Key terms
- Element: one value stored in the array.
- Index: the position of an element. Indexes start at 0 in C and C++.
- Size: the number of elements the array holds.
- Element type: the type shared by every element, such as
intordouble.
For double prices[4];, the element type is double, the size is 4, and the valid indexes are 0 through 3.
Declaring an array
The general form is the element type, the name, and the size in square brackets:
type name[size];
Two concrete examples:
double prices[4] = {1.25, 2.50, 3.75, 5.00};
char letters[3] = {'a', 'b', 'c'};
The initializer list is optional. A local array declared without one holds indeterminate values until you assign them.
Index and size
prices[1] is the second element, which is 2.5. A C-style array has no size() member, so your code either keeps the count itself or computes it with sizeof(prices) / sizeof(prices[0]) in the same function where the array is declared.
How arrays differ from related types
- C-style arrays have a fixed size, no size member, and no bounds checks.
std::array, added in C++11, has a fixed size like a C-style array, but it reports that size throughsize(), andat()checks the index.std::vectorcan grow and shrink while the program runs.
The c std::array topic covers the fixed-size type in more depth.
Elements can be more than numbers
Element types are not limited to built-in types. An element can be a struct, which is the idea behind array of structs in c, or a pointer to a function with a matching signature, which leads to c array of function pointers.