c - C中 union 的内存共享

标签 c unions

不幸的是,在线资源中对 Union in C 的特定行为的描述(如果需要,我可以列出一些)从一个来源到另一个来源有很大差异,在某些情况下还不够。其中一个资源说,您可以定义一个包含许多成员的 union ,但在任何给定时间只有一个成员可以包含一个值。 仅此而已。然后另一个资源说,在 union 中,当前存储其值的唯一成员将拥有内存。 所以,现在如果我运行这个程序,

#include <stdio.h>

union item
{
 int a;
 float b;
 char ch;
};

int main( )
{
 union item it;
 it.a = 12;
 it.b = 20.2;
 it.ch='z';
 printf("%d\n",it.a);
 printf("%f\n",it.b);
 printf("%c\n",it.ch);
 return 0;
}

我得到的输出是:

1101109626
20.199940
z

在线网站指出 ab 都已损坏,尽管我在这里略有不同,因为 b 接近 20.2。无论如何,现在如果我在开头写 char 然后写 a 和 b(仍然是相同的格式),我会看到 b 具有正确的值,但其他两个已损坏。但是,如果我将 b 声明为 int,则 ab 都是正确的。所以我推断,如果 union 的成员具有相同的格式,那么当您编写任何一个成员时,其他成员 WILL 包含相同的值(因为它们具有相同的格式),您可以阅读随时关闭没有任何问题。但是如果都是不同的格式,那么最后写的就是有效值。我没有找到明确说明这一点的在线资源。这个假设是否正确?

最佳答案

But if they are all of different format, then the one who was written last is only the valid value.

你几乎是正确的。


当您写入 union 的一个成员并读取另一个成员(不是最后写入的那个)时,行为是未指定的,这可能是陷阱表示。

来自 C11 n1570 草案的一个脚注(参见 6.5.2.3 中的脚注 95):

If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be a trap representation.

关于c - C中 union 的内存共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36155308/

相关文章:

c - 为什么会出现段错误?

php - Laravel 5 - 如何使用查询生成器或 Eloquent 在两个以上的表/查询中使用联合?

低冗长的 C 泛型继承

c++ - union 像类/结构一样使用

c - 从 C 数组中排除唯一值

c++ - 可以将Gtk +应用程序编译为在Gtk 2和3上运行

c - 字符串数组的单指针和双指针有什么区别

c - 我不明白指针在这段代码中是如何工作的?

c - gcc、严格别名和通过 union 转换

java - 是否可以从 JCuda 将数据发送到定义为 Union 的 GPU 内存?