8.3. Initializing ArraysIf you do not explicitly initialize an array variable, the usual rules apply: if the array has automatic storage duration, then its elements have undefined values. Otherwise, all elements are initialized by default to the value 0. (If the elements are pointers, they are initialized to NULL.) For more details, see the section "Initialization" in Chapter 11. 8.3.1. Writing Initialization ListsTo initialize an array explicitly when you define it, you must use an initialization list: this is a comma-separated list of initializers, or initial values for the individual array elements, enclosed in braces. An example: int a[4] = { 1, 2, 4, 8 }; This definition gives the elements of the array a the following initial values: a[0] = 1, a[1] = 2, a[2] = 4, a[3] = 8 When you initialize an array, observe the following rules:
As a result of these rules, all of the following definitions are equivalent: int a[4] = { 1, 2 }; int a[ ] = { 1, 2, 0, 0 }; int a[ ] = { 1, 2, 0, 0, }; int a[4] = { 1, 2, 0, 0, 5 }; In the final definition, the initializer 5 is ignored. Most compilers generate a warning when such a mismatch occurs. Array initializers must have the same type as the array elements. If the array elements' type is a union, structure, or array type, then each initializer is generally another initialization list. An example: typedef struct { unsigned long pin; char name[64]; /* ... */ } Person; Person team[6] = { { 1000, "Mary"}, { 2000, "Harry"} }; The other four elements of the array team are initialized to 0, or in this case, to { 0, "" }. You can also initialize arrays of char or wchar_t with string literals (see the section "Strings," later in this chapter). 8.3.2. Initializing Specific ElementsC99 has introduced element designators to allow you to associate initializers with specific elements . To specify a certain element to initialize, place its index in square brackets. In other words, the general form of an element designator for array elements is: [constant_expression] The index must be an integer constant expression. In the following example, the element designator is [A_SIZE/2]: #define A_SIZE 20 int a[A_SIZE] = { 1, 2, [A_SIZE/2] = 1, 2 }; This array definition initializes the elements a[0] and a[10] with the value 1, and the elements a[1] and a[11] with the value 2. All other elements of the array will be given the initial value 0. As this example illustrates, initializers without an element designator are associated with the element following the last one initialized. If you define an array without specifying its length, the index in an element designator can have any non-negative integer value. As a result, the following definition creates an array of 1,001 elements: int a[ ] = { [1000] = -1 }; All of the array's elements have the initial value 0, except the last element, which is initialized to the value -1. |