This code:
#include <stdio.h>
struct
{
int i;
const char* str;
} ar[] = {
1,"asd", //should be {1, "asd"},
2, "qwe", //should be {2, "qwe"},
3, "poi" //should be {3,"poi"}
};
int main()
{
printf("%s\n", ar[2].str);
}
Works perfectly fine, even though each element of array ar
should enclosed in braces (I would expect that at least). Why is this possible?
6.7.9 Initialization/20 states how such struct elements are initialized:
[..] If the initializer of a subaggregate or contained union begins with a left brace, the initializers enclosed by that brace and its matching right brace initialize the elements or members of the subaggregate or the contained union. Otherwise, only enough initializers from the list are taken to account for the elements or members of the subaggregate or the first member of the contained union; any remaining initializers are left to initialize the next element or member of the aggregate of which the current subaggregate or contained union is a part.
(emphasis mine)
So it's valid. And thus
ar[] = {
1,"asd",
2, "qwe",
3, "poi"
};
is equivalent to:
ar[] = {
{1,"asd"},
{2, "qwe"},
{3, "poi"}
};
and ar
contains 3 elements.