Search code examples
c++structmemberunions

C++ accessing a variable in a union struct


I am working with a library who has a struct defined as such:

typedef struct {
    int x;
    union {
        struct {
            y;
            union {
                int z;
            } innerStruct;
            char *a;
        } middleStruct;
    int q;
    } u;
} mainStruct;

How do I access char* a?

I have tried multiple methods. This works:

mainStruct *myStruct;
int d = myStruct->x;

But this does not work:

char *d = myStruct->a;

I can get x fine using the above method but not a. why?

I have never worked with unions before and I am forced to use this struct as part of the library I need. Thanks for the help in advance and sorry if I am butchering this question.


Solution

  • I can get x fine using the above method but not a. why?

    Because x is a member of mainStruct, but a isn't.

    a is a member of middleStruct which is a member of u which is a member of mainStruct. You can access members of union instances using the same syntax as you access members of non-union class instances. So, you can write myStruct->u.middleStruct.a

    P.S. The behaviour of mainStruct->u is undefined unless you first initialize mainStruct.