Array initialization

suggest change

An array is just a block of sequential memory locations for a specific type of variable. Arrays are allocated the same way as normal variables, but with square brackets appended to its name [] that contain the number of elements that fit into the array memory.

The following example of an array uses the typ int, the variable name arrayOfInts, and the number of elements [5] that the array has space for:

int arrayOfInts[5];

An array can be declared and initialized at the same time like this

int arrayOfInts[5] = {10, 20, 30, 40, 50};

When initializing an array by listing all of its members, it is not necessary to include the number of elements inside the square brackets. It will be automatically calculated by the compiler. In the following example, it’s 5:

int arrayOfInts[] = {10, 20, 30, 40, 50};

It is also possible to initialize only the first elements while allocating more space. In this case, defining the length in brackets is mandatory. The following will allocate an array of length 5 with partial initialization, the compiler initializes all remaining elements with the standard value of the element type, in this case zero.

int arrayOfInts[5] = {10,20}; // means 10, 20, 0, 0, 0

Arrays of other basic data types may be initialized in the same way.

char arrayOfChars[5]; // declare the array and allocate the memory, don't initialize

char arrayOfChars[5] = { 'a', 'b', 'c', 'd', 'e' } ; //declare and initialize

double arrayOfDoubles[5] = {1.14159, 2.14159, 3.14159, 4.14159, 5.14159};

string arrayOfStrings[5] = { "C++", "is", "super", "duper", "great!"};

It is also important to take note that when accessing array elements, the array’s element index(or position) starts from 0.

#include <iostream>
using namespace std;

auto main() -> int
{
    int array[5] = { 10, 20, 30, 40, 50 };
    std::cout << array[4];
    std::cout << array[0];
}
5010

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Arrays:
* Array initialization

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype