If I define an array without initializing all of the values, like so:
int x[10] = {1, 3, 5, 2, 9, 8, 4, 7, 6};
what happens if, for example, I reference x[9]
? What value is it fetching? Is it 0
because I haven't defined that value?
If I define an array without initializing all of the values, like so:
int x[10] = {1, 3, 5, 2, 9, 8, 4, 7, 6};
what happens if, for example, I reference x[9]
? What value is it fetching? Is it 0
because I haven't defined that value?
what happens if, for example, I reference x[9]?
It will be zero (as you found out). When you initialize one or more elements of an array, the rest of elements of the array are implicitly initialized to zero.
This is not because you haven't "defined" any value but the behaviour C standard mandates.
C11 draft, §6.7.9, Initialization
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
That means the x[9] will initialized to 0
as you have explicitly initialized the index range 0-8.
Similarly, if you have:
int i;
int j;
int *ptrs[10] = {&i, &j}; // an array of 10 pointers
The rest of the pointers, index range from 2-9 will be implicitly initialized to null pointers.
Initializer list will initialize array elements in increasing order of their index. If the size of initializer list is smaller than that of the size of the array then rest of the elements are initialized with 0
,