Union in Struct Error

前端 未结 2 538
刺人心
刺人心 2021-01-26 04:42

I have the following struct:

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

Whe

2条回答
  •  春和景丽
    2021-01-26 04:56

    If f is a pointer, then you may access "element" using f->element, or (*f).element

    Update: just saw that "element" is the union name, not a member of the struct. You may try

    union element {
        struct type3 *e;
        int val;
    } element;
    

    So the final struct would be like this:

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

    And now you can access element members like this, through a type1 *f:

    struct type1 *f;
    
    // assign f somewhere
    
    f->element.val;
    

提交回复
热议问题