Search code examples
cstructunions

Union in Struct Error


I have the following struct:

struct type1 {
    struct type2 *node;
    union element {
        struct type3 *e;
        int val;
    };
};

When initialising a pointer *f that points to an instance of type1 and doing something like: f.element->e or even just f.element, I get:

error: request for member ‘element’ in something not a structure or union

What am I overseeing here?


Solution

  • element is the name of the union, not the name of a member of type1. You must give union element a name:

    struct type1 {
    struct type2 *node;
        union element {
            struct type3 *e;
            int val;
        } x;
    };
    

    then you can access it as:

    struct type1 *f;
    f->x.e