我有一个结构
typedef struct foo {
int type;
int id[2];
int data[8];
} Foo;
这可以是两种不同的类型。如果 type==1
,那么它有一个 32 位的 id 和 8 个字节的存储空间,但是如果 type==2
,那么它有一个 64 位的 id,但是只能存放七个字节的数据。所以这两种类型在内存中占用相同的空间。但我想做
Foo foo1;
foo1.type = 1;
foo1.id = 1;
foo1.data = eightbytes;
Foo foo2;
foo2.type = 2;
foo2.id = 2;
foo2.data = sevenbytes;
这在 C 中可能吗?
最佳答案
是的,这是可能的:
typedef struct foo {
int type;
union {
struct {
int id;
int data[8];
} t1;
struct {
long id;
int data[7];
} t2;
} u;
} Foo;
您的用法将变为:
Foo foo1;
foo1.type = 1;
foo1.u.t1.id = 1;
foo1.u.t1.data = eightbytes;
Foo foo2;
foo2.type = 2;
foo2.u.t2.id = 2;
foo2.u.t2.data = sevenbytes;
关于C struct,其字段名称可以在上下文中引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41060857/