6

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.

Community
  • 1
  • 1
  • possible duplicate of [C and C++ : Partial initialization of automatic structure](http://stackoverflow.com/questions/10828294/c-and-c-partial-initialization-of-automatic-structure) – Jonathan Mee Nov 12 '14 at 21:14

2 Answers2

9

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.

Overv
  • 8,433
  • 2
  • 40
  • 70
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.

Gus
  • 151
  • 3
  • Sorry for my English. But I mean *how the structure will be initialized*. I'm interesting about language, not how author wants to use the code above. I slightly edited my question. –  Oct 27 '12 at 17:59
  • Ok here it is. An array like this reserves a block of memory in the data area of the program. The compiler in compile time initialises this memory with 0s. If it is a local variable the global block is copied to the stack in order to initialise it. Remember that this array of structures occupies a consecutive block of memory so by setting all the bytes to 0 you actually initialise the array. I hope I managed to answer you question. – Gus Oct 28 '12 at 07:17