7.3 Initializing Arrays
Arrays can be initialized when they are first created by specifying the initial values within curly braces { }:
- int values[5] = {7, 20, 1, 8, 15};
which results in the array
The literal values listed in the curly braces are assigned to the elements of the array one after the other in the order listed.
- If there are more initial values than there are elements specified by the array size in the declaration, the size of the array is increased to accommodate the entire sequence of initial values.
- If there the number of initial values is less than the array size specified in the array declaration, the size of the array will be as indicated in the declaration.
- The value indicating the size of the array can be omitted when initial values are provided. In this case, the array will be sized just large enough to hold all of the values.
Below, we create two additional arrays that are initialized to illustrate some of the points stated above:
- const int MAX_SIZE = 100;
- int main()
- {
- int codes[MAX_SIZE] = {5, 10, 15, 20, 25, 30, 35};
- int list[] = {1, 2, 3, 4, 5, 6};
- }
Note that you can not directly copy the contents of one array to another, nor can you assign the array variable of a static array to another array. For example, the following will result in a syntax error:
- codes = list;
To copy the contents from one array to another requires the use of a loop, which will be discussed in a later section.
|
Defining and Initializing an Array
type name[size] = {value1, value2, ...};
The initial values of an array can be specified when it is first created. The values must be provided as a sequence within a pair of curly braces (
{ }).
|
What is the resulting size of each of the three arrays declared above?
valueswill have 5 elements since the array is declared to have 5 elements and there are 5 initial values.codeswill have 100 elements since the array is declared to have 100 elements, but only 7 initial values are specified.listwill have 6 elements since there are 6 initial values and no array size was specified in the declaration.
Consider the array diagram below of the array illustrated on the first page of the chapter. Provide the declaration to create the array with the name limits.
- int limits[11] = {10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29};

