c - Unexpected output on initializing array by using both "Element-by-Element" & "Designated" techniques together -
c99 provides feature initialize arrays using both element-by-element
& designated
method as:
int a[] = {2,1,[3] = 5,[5] = 9,6,[8] = 4};
on running code:
#include <stdio.h> int main() { int a[] = {2,1,[3] = 5,[0] = 9,4,[6] = 25}; for(int = 0; < sizeof(a)/sizeof(a[0]); i++) printf("%d ",a[i]); return 0; }
(note element 0
initialized 2
, again initialised designator [0]
9
) expecting element 0
(which 2
) replaced 9
(as designator [0] = 9
) , hence o/p become
9 1 0 5 4 0 25
unfortunately wrong o/p came;
9 4 0 5 0 0 25
any explanation unexpected o/p?
the process of initializing array initializer basically:
- set index counter 0, , initialize entire array 0s
- go through initializer elements left right
- if initializer element has designated index, set index counter designated index
- store initializer element value @ index given index counter
- increment index counter
- go step 3 if there more initializer elements.
Comments
Post a Comment