Sams Teach Yourself C in 21 Days

(singke) #1
Initializing Arrays ..........................................................................................

You can initialize all or part of an array when you first declare it. Follow the array decla-
ration with an equal sign and a list of values enclosed in braces and separated by com-
mas. The listed values are assigned in order to array elements starting at number 0.
Consider the following code:
int array[4] = { 100, 200, 300, 400 };
For this example, the value 100 is assigned to array[0], the value 200 is assigned to
array[1], the value 300 is assigned to array[2], and the value 400 is assigned to
array[3].
If you omit the array size, the compiler creates an array just large enough to hold the ini-
tialization values. Thus, the following statement would have exactly the same effect as
the previous array declaration statement:
int array[] = { 100, 200, 300, 400 };
You can, however, include too few initialization values, as in this example:
int array[10] = { 1, 2, 3 };
If you don’t explicitly initialize an array element, you can’t be sure what value it holds
when the program runs. If you include too many initializers (more initializers than array
elements), the compiler detects an error. According to the ANSI standard, the elements
that are not initialized will be set to zero.

184 Day 8

Don’t rely upon the compiler to automatically initialize values. It is best to
Tip make sure you know what a value is initialized to by setting it yourself.

Initializing Multidimensional Arrays ............................................................

Multidimensional arrays can also be initialized. The list of initialization values is
assigned to array elements in order, with the last array subscript changing first. For
example:
int array[4][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
results in the following assignments:
array[0][0] is equal to 1
array[0][1] is equal to 2
array[0][2] is equal to 3
array[1][0] is equal to 4

14 448201x-CH08 8/13/02 11:21 AM Page 184

Free download pdf