gpt4 book ai didi

c++ - union的用法和乱码

转载 作者:太空宇宙 更新时间:2023-11-04 16:19:14 28 4
gpt4 key购买 nike

我有一些代码是关于 union 的用法,如下所示:

int main(){

typedef union{int a;char b[10];float c;}Union;

Union x,y = {100};
printf("Union x :%d| |%s| |%f \n",x.a,x.b,x.c );
printf("Union y :%d| |%s| |%f \n\n",y.a,y.b,y.c);

x.a = 50;
printf("Union x :%d| |%s| |%f \n",x.a,x.b,x.c );
printf("Union y :%d| |%s| |%f \n\n",y.a,y.b,y.c);

strcpy(x.b,"hello");
printf("Union x :%d| |%s| |%f \n",x.a,x.b,x.c );
printf("Union y :%d| |%s| |%f \n\n",y.a,y.b,y.c);

x.c = 21.50;
printf("Union x :%d| |%s| |%f \n",x.a,x.b,x.c );
printf("Union y :%d| |%s| |%f \n\n",y.a,y.b,y.c);

return 0;
}

在我编译并执行上面的代码后,我得到了这样的结果:

  Union x :0|     ||    |0.000000 
Union y :100| |d| |0.000000

Union x :50| |2| |0.000000
Union y :100| |d| |0.000000

Union x :1819043176| |hello| |1143141483620823940762435584.000000
Union y :100| |d| |0.000000

Union x :1101791232| || |21.500000
Union y :100| |d| |0.000000

不知为何y.b初始化为“d”?以及为什么 x.a 和 x.c 的值在之后发生了变化?为什么 strcpy(x.b,"hello") 不起作用?

最佳答案

严格按照类型双关标准,在狭窄的情况下期望是undefined behavior但实际上许多编译器都支持它,例如 gcc manual points 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.

我会推荐阅读 Understanding Strict Aliasing如果您打算大量使用双关语

y.b 的值为 b 因为 union 的所有元素都共享内存并且您用 100 初始化了 y > 在 ASCII 中是 b。这就是为什么 x 的其他字段在您修改一个字段时发生变化的原因,包括 strcpy 的情况,并且根据您的编译器,这可能是未定义的或明确定义的(在 gcc 的情况下,它是定义的)。

为了完整起见,C++ 草案标准部分 9.5 Union 段落 1 说(强调我的):

In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time. [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. —end note ] The size of a union is sufficient to contain the largest of its non-static data members. Each non-static data member is allocated as if it were the sole member of a struct.

关于c++ - union的用法和乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19136881/

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