gpt4 book ai didi

C- 结构和 union

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:10 25 4
gpt4 key购买 nike

C 标准声明,只有 union 的成员存储在相同 地址,因此,我们一次只能访问一个成员。由于编译器覆盖存储对于 union 成员,更改一个成员会改变之前存储在任何其他成员中的任何值。因此,如果我们尝试访问之前存储的成员的值,则该值将毫无意义或未定义。现在这是我的问题: -

struct catalog_item
{
int stock_number;
double price;
int item_type;
union
{
struct
{
char title[TITLE_LEN+1];
char author[AUTHOR_LEN+1];
int num_pages;
} book;
struct
{
char design[DESIGN_LEN+1];
} mug;
struct
{
char design[DESIGN_LEN+1];
int colors;
int sizes;
} shirt;
} item;
} c;

现在如果做了下面的事情

strcpy(c.item.mug.design, "Butterfly");

那么下面两个都有相同的值

printf("%s",c.item.mug.design);          //1

printf("%s",c.item.shirt.design);        //2

为什么“2”的结果不是未定义或无意义的?

最佳答案

这不是未定义的行为,而是实现定义的行为,如果我们查看 C99 draft standard 脚注 82 说:

If the member used to access 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 中是受支持的,您应该阅读特定的编译器文档。例如,如果您检查 Structures, unions, enumerations, and bit-fields实现定义的行为部分在 gcc 手册中它指向 here for Type-punning我们可以在 -fstrict-aliasing 部分看到:

The practice of reading from a different union member than the one most recently written to (called “type-punning”) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type.

但有一些注意事项,您应该继续阅读 strict aliasing了解所有细节,this article是比较温和的介绍。

为了完整性,部分 3.4.1实现定义的行为定义为:

unspecified behavior where each implementation documents how the choice is made

标准附件 J.1 Unspecified behavior 列出了标​​准涵盖的未指定行为,包括以下行:

The value of a union member other than the last one stored into (6.2.6.1).

关于C- 结构和 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18576300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com