gpt4 book ai didi

c - 以下代码的输出.. union

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:48 26 4
gpt4 key购买 nike

谁能解释一下为什么下面的代码会打印 20 而不是 10?

谢谢

#include<stdio.h>

int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a);
return 0;
}

最佳答案

根据 union 的定义:您不能同时使用 v.av.b,因为这两个字段共享相同的地址。引用标准:

A union type describes an overlapping nonempty set of member objects, each of which has an optionally specified name and possibly distinct type.

在这里,一旦您分配给 v.b,您就会覆盖 v.a。在你的情况下,事情不会变得难看,因为两个变量具有相同的类型,但想象一下如果 afloatb例如一个字符。

如果您的目标是让 var 成为包含两个不同 int 的复合变量,那么您应该使用 struct,而不是 union

关于c - 以下代码的输出.. union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4233489/

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