使用 C 中的结构联合 [英] Working with a union of structs in C
问题描述
假设我有以下类型:
typedef struct TYPEA
{
int type;
char[12] id;
} TYPEA;
typedef struct TYPEB
{
int type;
int value;
} TYPEB;
我想使用创建这些类型和int"的联合,这样我就可以访问类型"int,而无需知道联合中存储的是 TYPEA 还是 TYPEB(int 的值让我确定哪个实际上存储在那里).但我无法获得正确的语法.
I want to use create a union of these types and 'int', so that I can access the "type" int without needing to know whether TYPEA or TYPEB is stored in the union (the value of int lets me determine which is actually stored there). I can't get the right syntax though.
我的工会:
typedef union MEMBER
{
int type;
struct TYPEA a;
struct TYPEB b;
} MEMBER;
通过以下方式访问联合:
The union is accessed via:
typedef struct WRAPPER
{
union MEMBER* member;
struct WRAPPER* next;
} WRAPPER;
问题:
- (使用 'w' 作为指向分配的 WRAPPER 结构的指针)使用
w->member->a.id
访问会在非结构体中提供对成员 'id' 的请求或工会. - 我可以将一个指向已被 malloc 的 TYPEA/B 的指针直接分配给 w->member 吗?或者联合需要特别malloced?
- (With 'w' as a pointer to an allocated WRAPPER struct) Accessing using
w->member->a.id
gives "request for member 'id' in something not a structure or union. - Can I assign a pointer to an already malloc'd TYPEA/B to w->member directly? Or does a union need to be malloced specially?
谢谢.
推荐答案
- 使用
w->member->type
. - 您需要专门分配
union
.
一个可能引起误解的注释是 union
持有 int
、TYPEA
或 TYPEB
,所以特别是你不能依靠联合中的 int type;
来告诉你联合持有哪个 struct
.
One note that may be a point of misunderstanding is that the union
holds EITHER the int
, or TYPEA
, or TYPEB
, so in particular you cannot rely on your int type;
in the union to tell you which struct
the union holds.
编辑以回复评论中的问题:
你可能想要这样的东西:
You probably want something like this:
struct TYPEA {
char data[30]; // or whatever
};
struct TYPEB {
double x, y; // or whatever
};
struct some_info {
int type; // set accordingly
union {
struct TYPEA a;
struct TYPEB b;
} data; // access with some_info_object.data.a or some_info_object.data.b
};
这篇关于使用 C 中的结构联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!