结构错误中的联合
我有以下结构:
struct type1 { struct type2 *node; union element { struct type3 *e; int val; }; };
当初始化一个指向type1
实例的指针*f
并执行类似: f.element->e
或甚至只是f.element
,我得到:
error: request for member 'element' in something not a structure or union
我在这里监督什么?
element
是union的名称,而不是type1
成员的名称。 您必须为union element
一个名称:
struct type1 { struct type2 *node; union element { struct type3 *e; int val; } x; };
然后你可以访问它:
struct type1 *f; f->xe
如果f是指针,则可以使用f-> element或(* f).element访问“element”
更新:只看到“元素”是联合名称,而不是结构的成员。 你可以试试
union element { struct type3 *e; int val; } element;
所以最终的结构将是这样的:
struct type1 { struct type2 *node; union element { struct type3 *e; int val; } element; };
现在你可以通过type1 * f访问这样的元素成员:
struct type1 *f; // assign f somewhere f->element.val;