Programming in C

(Barry) #1
Initializing Arrays 107

Arrays of characters are initialized in a similar manner; thus the statement

char letters[5] = { 'a', 'b', 'c', 'd', 'e' };


defines the character array lettersand initializes the five elements to the characters
'a','b','c','d',and 'e',respectively.
It is not necessary to completely initialize an entire array. If fewer initial values are
specified, only an equal number of elements are initialized.The remaining values in the
array are set to zero. So the declaration


float sample_data[500] = { 100.0, 300.0, 500.5 };


initializes the first three values of sample_datato 100.0,300.0,and 500.5, and sets the
remaining 497 elements to zero.
By enclosing an element number in a pair of brackets, specific array elements can be
initialized in any order. For example,


float sample_data[500] = { [2] = 500.5, [1] = 300.0, [0] = 100.0 };


initializes the sample_dataarray to the same values as shown in the previous example.
And the statements


int x = 1233;
int a[10] = { [9] = x + 1, [2] = 3, [1] = 2, [0] = 1 };


define a 10-element array and initialize the last element to the value of x + 1(or to
1234 ), and the first three elements to 1 , 2 ,and 3 ,respectively.
Unfortunately, C does not provide any shortcut mechanisms for initializing array ele-
ments.That is, there is no way to specify a repeat count, so if it were desired to initially
set all 500 values of sample_datato 1 , all 500 would have to be explicitly spelled out. In
such a case, it is better to initialize the array inside the program using an appropriate for
loop.
Program 7.5 illustrates two types of array-initialization techniques.


Program 7.5 Initializing Arrays


#include <stdio.h>


int main (void)
{
int array_values[10] = { 0, 1, 4, 9, 16 };
int i;


for ( i = 5; i < 10; ++i )
array_values[i] = i * i;

for ( i = 0; i < 10; ++i )
printf ("array_values[%i] = %i\n", i, array_values[i]);

return 0;
}

Free download pdf