假设我有以下代码,定义了一个结构和一个 union :
struct Foo
{
int i;
float f;
};
union Bar
{
struct Foo foo;
char buf[10];
};
将指针分配给struct Foo
类型的对象来代替指向union Bar
类型的指针并随后这样使用它是否安全:
struct Foo fooVar;
union Bar* barPtrVar = (union Bar*) &fooVar;
bar->foo.i = 1000;
bar->foo.f = 0.5f;
只要我们确定只使用union Bar
的foo
成员?
我记得在 C 中,指向结构的指针与指向它的第一个成员的指针相同,因此它们有时可以互换,因此尽管类似的逻辑可能适用于此处。
最佳答案
即使您从 buf
成员读取(在某种程度上),这种用法也是安全的。
C standard 第 6.5p7 节给出以下别名规则:
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
- a type compatible with the effective type of the object,
- a qualified version of a type compatible with the effective type of the object,
- a type that is the signed or unsigned type corresponding to the effective type of the object,
- a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
- an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
- a character type.
您的用例属于倒数第二个要点,并从 buf
成员读取到 buf[sizeof(struct Foo)-1]
根据最后一个要点是允许的。
关于特定类型的指针可以分配给指向包含与其成员之一相同类型的 union 体的指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74156873/