gpt4 book ai didi

c++ - 以下 union 中的值是如何分配的?

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

在下面的代码中,是否可以预测 int 的值(如何?),还是只是垃圾?

union a
{
int i;
char ch[2];
};
a u;
u.ch[0] = 0;
u.ch[1] = 0;
cout<<u.i;
}

最佳答案

我会说这取决于 intchar 的大小。 union 包含最大变量的内存。如果 int 是 4 个字节而 char[2] 代表 2 个字节,则 intchar 消耗更多的内存-array,因此您不会通过设置所有 char-变量将完整的 int-memory 初始化为 0。这取决于您的内存初始化机制,但基本上 int 的值看起来是随机的,因为额外的 2 个字节填充了未指定的值。

此外,在我看来,填充 union 的一个变量并读取另一个变量正是使 union 不安全的原因。

如果你确定int是最大的数据类型,你可以通过写初始化整个union

union a
{
int i;
char ch[2];
};

void foo()
{
a u = { 0 }; // Initializes the first field in the union
cout << u.i;
}

因此,将最大的类型放在并集的开头可能是个好主意。虽然这并不能保证当所有位都设置为 0 时,所有数据类型都可以被视为零或空。

关于c++ - 以下 union 中的值是如何分配的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11897301/

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