I don't understand this nested struct

2019-09-17 10:33发布

问题:

The struct is:

struct 
{    
    int x;
    struct 
    {
        int y, z;
    } nested;
}
i={.nested.y = 5, 6, .x = 1, 2};

Question: The result is i.nested.y = 2; i.nested.z = 6;

I cannot get or understand this, the inner one is also a struct but union, so could anyone help me?

回答1:

Ok, first of all let me say that this is a terrible way to initialize a struct, and if it's a homework question - it's not a very good one either.
However, given the problem at hand, what I believe is happening in the initialization is this: first, y is initialized to 5, and z, being the next member in the struct, is initialized to 6. Then, x is initialized to 1 and the next member in the struct, in this case y, is initialized to 2 (which overwrites the 5).

Something important to note as well, is that the nested struct isn't a union, but a struct - first of all, because that's what the code says, but also because if it were a union - it would be impossible in this case for y and z to have different values, since both would be kept in the same location in the memory.



标签: struct union