使用 union 的名称访问 union 成员 [英] Accessing the union members using the name of union
本文介绍了使用 union 的名称访问 union 成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何访问结构中存在的联合成员?
How can I access the union members which exist inside the structure?
考虑代码片段:
struct Emp {
char name[20];
union address {
char addr[50];
};
};
struct Emp e;
使用 e
,如何在不创建任何联合对象的情况下访问 addr
类型?
Using e
, how do I access the addr
type without creating any union object?
推荐答案
未命名结构C11 和 GCC 扩展中支持 structs/unions 中的/union 字段.如果开启了这个功能,你可以直接使用e.addr
.请注意,标签名称也应为空.
Unnamed struct/union fields within structs/unions is supported in C11 and also GCC extension. If this feature is on, you can use e.addr
directly. Note that the tag name should be empty, either.
struct Emp {
char name[20];
union {
char addr[50];
};
};
如果不支持,你需要给union
一个名字并使用e.u.addr
.
If it's not supported, you need to give the union
a name and use e.u.addr
.
struct Emp {
char name[20];
union address {
char addr[50];
} u;
};
这篇关于使用 union 的名称访问 union 成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文