c99

C99 struct member initialization


Following code is wrt to C99 standards.

struct obj{
    int a1[2];
    int a2[2];
};


int main(void) {
    struct obj dog = {.a2[0] = 0, .a1[1]= 2, 3, .a2[1]=4};
    printf("%d,%d,%d, %d\n", dog.a1[0], dog.a1[1], dog.a2[0], dog.a2[1]);

}


Output is: 0,2,3, 4

Why is the value of a2[0] coming as 3? Any link for c99 struct initalization?


Solution

  • A struct is just a sequence of members, and if you don't specify which member you want to assign value to at initialization, it will just move to the next member and assign that value there. When you initialize the dog object, you use the arguments 0, 2, 3, and 4. I don't know if it is intentional, but a2[0] wasn't implicitly stated, but an argument (3) was still provided to it. You can re-write your code to be

    struct obj dog = { 0, 2, 3, 4};
    

    and it would still produce the same results. However, I wouldn't suggest doing that as it makes the code less readable.