Unexpected output on initializing array by using both “Element-by-Element” & “Designated” techniques together

懵懂的女人 提交于 2019-12-10 17:52:57

问题


C99 provides a feature to initialize arrays by using both element-by-element & designated method together as:

int a[] = {2,1,[3] = 5,[5] = 9,6,[8] = 4};

On running the code:

#include <stdio.h>

int main()
{
   int a[] = {2,1,[3] = 5,[0] = 9,4,[6] = 25};
   for(int i = 0; i < sizeof(a)/sizeof(a[0]); i++)
          printf("%d    ",a[i]);

   return 0;
 }

(Note that Element 0 is initialized to 2 and then again initialised by designator [0] to 9) I was expecting that element 0(which is 2) will be replaced by 9(as designator [0] = 9) and hence o/p will become

   9    1   0   5   4   0   25

Unfortunately I was wrong as o/p came;

   9    4   0   5   0   0   25

Any explanation for unexpected o/p?


回答1:


The process of initializing an array with an initializer is basically:

  1. set the index counter to 0, and initialize the entire array to 0s
  2. go through the initializer elements from left to right
  3. if the initializer element has a designated index, set the index counter to the designated index
  4. store the initializer element value at the index given by the index counter
  5. increment the index counter
  6. go back to step 3 if there are any more initializer elements.



回答2:


Using designated initializers combined with element initializers implies positions based on the designated initializers.

So if you were to do:

int a[] = {2, 1, [3] = 5, 6};

The result ought to be:

2 1 0 5 6

Not:

2 1 0 6

Note that 6 occupies position 3 in the initializer, but its resulting position is implied by the preceding designated initializer (which uses position 3). The position following the one used by the designated initializer is 4, so that is where the 6 is placed.



来源:https://stackoverflow.com/questions/17384561/unexpected-output-on-initializing-array-by-using-both-element-by-element-de

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!