Start learning free

LESSON 91 OF 409 · ARRAYS I

Static Arrays in C++: Declaring and Initializing Fixed Arrays

Lesson Read the full explanation

When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.

In C++, we use arrays to store several pieces of data in one place. The items in an array must be of the same data type.

A static array or fixed array is an array for which the size / length is determined when the array is created and/or allocated.


Creation:

We create a static array by writing the data type of its elements, followed by the array's name and the array's length inside []:

string arrayOfStrings[5];

In this program we created an array named arrayOfStrings that consists of 5 String items.

These 5 items are initialized with empty strings "" automatically.


Creation & Initialization:

There is a way to initialize an array at creation by using the = operator with an opening bracket, end it with a closing bracket, and put a comma between each entry, like this:

string arrayOfStrings[] = {"AlgoCademy", "coding", "static arrays"};

We created an array named arrayOfStrings which consits of 3 string items: "AlgoCademy", "coding" and "static arrays".


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    C++ · ARRAYS I

    Static Arrays in C++, explained

    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 string are built by their default constructor, so arrayOfStrings starts with five empty strings.
    • Elements of a built-in type such as int are 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 writing numbers[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, with std::copy, or use std::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 a std::array or std::vector.
    • Using a non-constant length. Use a const or constexpr value, or switch to vector.

    The exercise, step by step

    1. Create numbers. It is an int array with 20 elements, so the type is int and the declaration is numbers[20]. Add = {} so every element starts at 0 instead of garbage.
    2. Create fruits. It is a string array 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], or type name[] = {values} to let the compiler count.
    • Local arrays of int and 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::vector or std::array.
    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free