C++ array initialization

There are many ways to initialize an array :

An array can be initialized in the declaration by writing a comma-separated list of values enclosed in braces following an equal sign.

int number[12] = {1, 8, 1, 2, 1, 3, 4, 7, 9, 2, 5, 3};
This looks like an assignment, assignment statements with arrays are not allowed, and this syntax is legal only in a declaration.
Size can be set from initial value list
If the size is omitted, the compiler uses the number of values.
int number[] = {1, 8, 1, 2, 1, 3, 4, 7, 9, 2, 5, 3};
No default value
If an array has no initialization, the values are undefined.
char name[20];
Missing initialization values use zero
If an explicit array size is specified, but an shorter initialization list is specified, the unspecified elements are set to zero.
int number[10] = {7, 8, 6};
This not only initializes the first three values, but all remaining elements are set to 0.0. To initialize an array to all zeros, initialize only the first value.
float average[10] = {0.0}; // All 10 values initialized to zero.
Initialization of character arrays
Character arrays can be initialized on the right by writing a double-quoted string.
char name[] = "Yogesh"; // Array size is 6.

Run Time Initialization

An array can be explicitly initialized at run time. This approach is usually applied while initializing array from user.

int number[3];
cin>>number[0]>>number>>[1]>>number[2];

Important points about Array
  • index of array starts with zero (0).
  • index of last element in array is n-1, where n is the size of the array
  • array has static memory allocation. i.ememory size once allocated for an array cannot be changed.

0 Comments