Can I assign a value to one union member and read the same value from another?

时间:2015-12-10 01:30:02

标签: c struct language-lawyer unions

Basically, I have a

struct foo {
        /* variable denoting active member of union */
        enum whichmember w;
        union {
                struct some_struct my_struct;
                struct some_struct2 my_struct2;
                struct some_struct3 my_struct3;
                /* let's say that my_struct is the largest member */
        };
};

main()
{
        /*...*/
        /* earlier in main, we get some struct foo d with an */
        /* unknown union assignment; d.w is correct, however */
        struct foo f;
        f.my_struct = d.my_struct; /* mystruct isn't necessarily the */
                                /* active member, but is the biggest */
        f.w = d.w;
        /* code that determines which member is active through f.w */
        /* ... */
        /* we then access the *correct* member that we just found */
        /* say, f.my_struct3 */

        f.my_struct3.some_member_not_in_mystruct = /* something */;
}

Accessing C union members via pointers seems to say that accessing the members via pointers is okay. See comments.

But my question concerns directly accessing them. Basically, if I write all the information that I need to the largest member of the union and keep track of types manually, will accessing the manually specified member still yield the correct information every time?

2 个答案:

答案 0 :(得分:1)

Yes your code will work because with an union the compiler will share the same memory space for all the elements.

For example if: &f.mystruct = 100 then &f.mystruct2 = 100 and &f.mystruct3 = 100

If mystruct is the largest one then it will work all the time.

答案 1 :(得分:0)

Yes you can directly access them. You can assign a value to a union member and read it back through a different union member. The result will be deterministic and correct.