特定类型的指针可以分配给指向包含与其成员之一相同类型的 union 体的指针吗?

标签 c pointers struct c99 unions

假设我有以下代码,定义了一个结构和一个 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 Barfoo成员?

我记得在 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/

相关文章:

在成本和重量限制内计算最佳可能的元素组合

c - 为什么我得到 : "error: assignment to expression with array type"

python - 在Python中解压ripemd160结果

java - Pebble 应用程序未从手机接收字符串

c - 子进程之间的 UNIX 管道

c++ - 用于绘制 C/C++ 结构、指针等的快速草图工具

c - 如何设置指针无效?

C - 将结构内部的指针重新分配给结构外部的指针

c++如何将文件解析为结构 vector

c - 从 lex 中的 while 循环中断