Union in Struct Error

六月ゝ 毕业季﹏ 提交于 2019-12-31 07:35:39

问题


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?


回答1:


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



回答2:


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;


来源:https://stackoverflow.com/questions/13037832/union-in-struct-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!