假设我有这个定义:
struct A {
union {
struct {
T1 f1;
T2 f2;
T3 f3;
...
};
char bytes[...];
};
有没有办法,在标准 C(或 gnu-c++14,据我所知,在一定程度上允许 union 类型双关)中自动将 bytes
数组的大小设置为和它union
的未命名结构一样大?
最佳答案
为了匹配匿名结构的大小,它必须不是匿名的,但在标准 C 中,您无法透明地寻址其成员。
typedef int T1,T2,T3; //example types
struct name{ //originally anonymous struct given a name
T1 f1;
T2 f2;
T3 f3;
};
struct A{
union {
struct name embedded;
char bytes[sizeof(struct name)];
//^can size it now that is has a name
} ;
}u;
在扩展 C(-fms-extensions
/-fplan9-extensions
使用 gcc)下,您可以执行以下操作:
typedef int T1,T2,T3;
struct name{
T1 f1;
T2 f2;
T3 f3;
};
struct A{
union {
struct name; //embed struct name transparently
char bytes[sizeof(struct name)];
} ;
}u;
但无论如何,这一切都不是必需的,因为 C 标准明确允许您将任何对象重新解释为 char 数组,而不会导致任何未定义的行为(只需将指向该对象的指针转换为 char*
并假装您是读取 char
数组)。
编辑:如果您需要通过 char 以外的类型重新解释,您可以使用宏,如下所示:
typedef int T1,T2,T3;
#define ANON_STRUCT \
struct { \
T1 f1; \
T2 f2; \
T3 f3; \
}
struct A{
union {
ANON_STRUCT;
ANON_STRUCT named_anon;
#if __cplusplus
char bytes[sizeof(named_anon)];
#else
char bytes[sizeof(ANON_STRUCT)];
#endif
} ;
}u;
但上次我检查过您不能在 C++ 中使用 union 进行重新解释(仅在 C 中)——您必须坚持使用当前事件的成员。
关于c - C 中结构的字节数组类型双关语大小的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53127433/