What are the contents of a[]?
int a[ ] = {4 , 9, 1, 8, [0]=5, 7};
I tried printing it out with:
int main () {
int a[ ] = {4 , 9, 1, 8, [0]=5, 7};
for(int i = 0; i < 10; i++) {
printf("%d\n", a[i]);
}
return 0;
}
The result:
5
7
1
8
-1558310176
712
While the answer choices available are:
a) 5, 9, 1, 8, 7
b) 4, 9, 1, 8, 5, 7
c) 5, 4, 9, 1, 8, 7
d) 4, 9, 1, 8, 7
e) 4, 9, 1, 8, 0, 5, 7
>Solution :
When an initializer is given for an aggregate type (i.e. an array, struct, or union), the initializer for the subobjects are applied in order.
Given this initializer:
int a[ ] = {4 , 9, 1, 8, [0]=5, 7};
Array elements 0 – 3 are first initialized with the values 4, 9, 1, 8 respectively. Then the designated initializer [0]=5 initializes array element 0 to 5, overwriting the prior initialization of 4. This then makes the current subobject element 0, so the next initializer applies to the next object after that, which is index 1. Then causes index 1 to be initialized with the value 7, overwriting the prior initialization of 9.
So the above initializer creates an array of int of 4 elements initialized with the values 5, 7, 1, 8.
Also, given that you’re printing 10 elements when the array only contains 4, you invoke undefined behavior when attempting to read past the end of the array.