UNION IN C(输出是什么)
union a
{
int x;
char a[2];
}
如果我们将 512 值赋给 x 并尝试打印 a[0] 和 a[1] 那么输出是什么 请解释一下如何?
union a
{
int x;
char a[2];
}
If we assign 512 value to x and try to print a[0] and a[1] then what will be the output
please explain how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C 中的联合共享相同的内存空间,即 x 和 a[2] 都从相同的内存位置开始。当您将值分配给其中一个时,另一个会被覆盖。
在你的例子中,当你将 512 分配给 x 时,你也会将它的字节写入 char,就像 Fernando Miguélez 刚刚解释的那样......
Unions in C share same memory space, that is, both x and a[2] start at the same memory location. When you assign the value to one of them, the other gets overwritten.
In your case, when you assign 512 to x, you'll write it's bytes to char as well, like Fernando Miguélez just explained...
这取决于你运行它的计算机的字节序:
联合实际上对你的 int 和你的字符使用相同的内存,所以,
(实际上,我可能有小和大字节序的错误方式)
It depends on the endian-ness of the computer you run it on:
union in effect uses the same memory for your int and your chars, so,
(actually, I might have little & big endian the wrong way around)
我取决于平台的字节顺序。在小端平台(Intel)上,a[0] 将具有整数的最低有效字节(4 个字节),因此 a[0] 将保存 0x00 和 a[1] 0x02
I the depends on the endianess of the platform. On little-endian platforms (Intel) a[0] will have the least significant byte of the integer (4 bytes), so a[0] will hold 0x00 and a[1] 0x02
根据该标准,写入联合体的一个成员然后从另一个成员读取的结果是未定义的。几乎任何事情都可能发生。
实际上,如果在小端机器上运行代码,a[0] 可能是 0,a[1] 可能是 2。在 16 位大端机器上,a[0] 可能是 2 a[1] 将为 0。在 32 位大端机器上,(不存在,正如您所定义的那样)a[2] 将为 2,并且 a[0]、a[1]、& ;a[3] 将为 0。
According to the standard, the result of writing to one member of a union, then reading from another isn't defined. Just about anything could happen.
Realistically, if you run the code on a little-endian machine, a[0] will probably be 0, and a[1] will probably be 2. On a 16-bit big-endian machine, a[0] would be 2 and a[1] would be 0. On a 32-bit big-endian machine, (the nonexistent, as you've defined things) a[2] would be 2, and a[0], a[1], &a[3] would be 0.