C++ array initialization

Photo by JJ Ying on Unsplash

C++ array initialization

·

2 min read

What's an array

An array is a data structure that is similar to a standard library-type vector, but it differs from a vector in the trade-off between performance and flexibility. Similar to vectors, arrays are also containers for objects of the same type. These objects don't have a name, and they can be accessed via their location. The difference from a vector is that the size of an array is fixed and elements cannot be added to it arbitrarily. Due to the size of the array being fixed, for certain special applications, the program has better runtime performance but correspondingly loses some flexibility.

Explicitly initialize array elements

Elements of an array can be initialized using list initialization, in which case the dimensions of the array can be omitted. If no dimension is specified during declaration, the compiler will calculate and infer it based on the number of initial values provided; conversely, if a dimension is specified, then the total number of initial values should not exceed the specified size. If there are more dimensions than the initial values provided, then only those elements that have been initialized with provided values will be assigned while the remaining elements will be initialized to their default value.

const unsigned sz = 3;
int a1[sz] = {0, 1, 2};    // There are 3 elements
int a2[] = {0, 1, 2};    // The array has three dimension
int a3[5] = {0, 1, 2};    // Equals a3[] = {0, 1, 2, 0, 0}
string a4[3] = {"hi", "bye"};    // Equals a4[] = {"hi", "bye", ""}
int a5[2] = {0, 1, 2};    // Error, too many elements

The special nature of character arrays

char a1[] = {'c', '+', 'c'};    // There is no null characters
char a2[] = {'c', '+', '+', '\0'};    // There is a null character
char a3[] = "c++";    // Automatically add a null character to indicate the end of the string
const char a4[6] = "Deniel"; // Error, there is no place to put a null character

Initialize the array of member variables

class A {
public:
    A();
private:
    int mArray[5];
    ...
}

A::A()
    : mArray{0, 1, 2}    // Equals mArray[] = {0, 1, 2, 0, 0}
{
}