What happens when there is partial initialization of an array of struct in C?

限于喜欢 提交于 2019-12-10 13:55:27

问题


What does this code mean?

struct foo_t {
    int a;
    int b;
} foo[10] = {{0,0}}

foo[0] is {0,0}, but what about the rest? How does the C standard handle this?

ADDED. I founded an exhaustive answer here. I think my question should be deleted.


回答1:


The entire array will be initialized with structs with the value 0 for both a and b. This is similar to the following case with a primitive value:

int foo[10] = {0};

Where every integer in the array will be initialized with the value 0.

The C99 standard specifies the following:

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.




回答2:


A value of 0 usually means the end of a list. By this I mean that when you iterate such a list and you encounter this value toy know that you have reached the end. I suppose that whoever created this ad something like this in his mind. If you search through the code you might find a fragment of code that sets a zero value after appending a value in the list.



来源:https://stackoverflow.com/questions/13104767/what-happens-when-there-is-partial-initialization-of-an-array-of-struct-in-c

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