What a static array is
A static array, also called a fixed-size array, is a block of elements of the same type stored one after another in memory. Its length is part of its type and is fixed when the program is compiled. A variable declared as int numbers[20] holds exactly 20 int values for its whole life: it can neither grow nor shrink. When you need a collection that changes size, use std::vector instead. A static array is the right choice when the size is known up front and small.
Declaring an array
Write the element type, the name, and the length in square brackets:
string arrayOfStrings[5]; // five strings
int scores[3]; // three ints
The length must be a constant the compiler knows, such as the literal 5 or a const int initialized with a literal. A plain variable like int n = 5; int a[n]; is not standard C++, although some compilers accept it as an extension.
What the elements contain depends on their type:
- Elements of a class type such as
stringare built by their default constructor, soarrayOfStringsstarts with five empty strings. - Elements of a built-in type such as
intare not initialized when the array is a local variable. They hold whatever was in that memory before, and reading them is a bug.
Initializing an array
List the values in braces, separated by commas:
string arrayOfStrings[] = {"AlgoCademy", "coding", "static arrays"};
When there is an initializer, the brackets can be empty and the compiler counts the values: this array has 3 elements. If you do give a length, the list may be shorter, and the remaining elements are set to zero (or to empty strings):
int part[5] = {1, 2}; // 1 2 0 0 0
int zeros[20] = {}; // all 20 elements are 0
Empty braces are the usual way to get a zeroed int array. A list longer than the length is a compile error: int a[3] = {1, 2, 3, 4}; fails with too many initializers for 'int [3]'.
Using the elements
Elements are numbered from 0, and you read or change them with square brackets:
string fruits[] = {"mango", "kiwi", "grapefruit"};
fruits[1] = "plum"; // replace "kiwi"
cout << fruits[0] << endl; // mango
for (const string& fruit : fruits) {
cout << fruit << endl; // mango, plum, grapefruit
}
The number of elements is sizeof(fruits) / sizeof(fruits[0]), which is 3 here, or std::size(fruits) in C++17. Both work only where the compiler still sees the real array.
Mistakes to avoid
- Going out of bounds. For
int numbers[20]the valid indexes are 0 to 19. Reading or writingnumbers[20]is undefined behaviour: C++ does not check, so the program may crash, print garbage, or appear to work. - Reading uninitialized elements. A local
int numbers[20];holds leftover values. Write= {}when you want zeros. - Assigning one array to another.
int b[3]; b = a;does not compile (invalid array assignment). Copy element by element, withstd::copy, or usestd::array, which can be assigned. - Measuring an array inside a function. An array passed to a function turns into a pointer to its first element. In
void f(int a[]),sizeof(a)is the size of a pointer (8 bytes on a 64-bit machine), not of the array. Pass the length as a second parameter, or take astd::arrayorstd::vector. - Using a non-constant length. Use a
constorconstexprvalue, or switch tovector.
The exercise, step by step
- Create
numbers. It is anintarray with 20 elements, so the type isintand the declaration isnumbers[20]. Add= {}so every element starts at 0 instead of garbage. - Create
fruits. It is astringarray filled from a brace list with"mango","kiwi"and"grapefruit". The brackets stay empty, because the compiler counts the three values.
int numbers[20] = {};
string fruits[] = {"mango", "kiwi", "grapefruit"};
As a check, sizeof(numbers) / sizeof(numbers[0]) is 20 and sizeof(fruits) / sizeof(fruits[0]) is 3. The lesson writes string without the std:: prefix; in your own file, add using namespace std; or write std::string, with #include <string>.
Key takeaways
- A static array has a fixed length, known at compile time, and elements of one type.
- Declare it as
type name[length], ortype name[] = {values}to let the compiler count. - Local arrays of
intand other built-in types start with garbage. Use= {}for zeros. - Indexes run from 0 to length minus 1, and C++ does not check them.
- When the size must change, or you want to pass the array around safely, use
std::vectororstd::array.
