当其他成员设置为新值时,C 联合成员给出特定/错误的值.为什么这个输出在 C 中的以下代码中? [英] C union member gives particular/wrong value when other member is set to a new value. Why is this output in following code in C?

查看:22
本文介绍了当其他成员设置为新值时,C 联合成员给出特定/错误的值.为什么这个输出在 C 中的以下代码中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
int main()
{
  union Data
  {
    char str[20];    
    int i;
    float f;
  }data;

  data.i=20;
  data.f=220.5;
  printf("%d\n",(data.i));

  return 0;
}

输出为:1130135552.我在 Ubuntu 16.04 LTS 上使用了 gcc 编译器.

The output is:1130135552. I used gcc complier on Ubuntu 16.04 LTS.

有人能解释一下输出吗?

Can someone explain the output?

成员data.idata.f占用相同的内存位置,所以输出应该是220.但为什么输出是1130135552?

The members data.i and data.f occupy same memory location, so output should be 220. But why output is 1130135552?

推荐答案

正如您已经知道的那样,union 在内部成员之间共享内存位置.union 编译器分配的内存等于成员的最大大小,并为所有成员使用相同的内存.

As you are already aware that union shares memory location between the members inside. In case of union compiler allocated the memory equal to the max size of the member and use the same memory for all the members.

因此,当您执行 data.f=220.5; 时,if 之间的共享内存位置持有 data.i=20; 被覆盖为一个新值 (220.5),二进制表示如下:

Hence when you execute data.f=220.5;, shared memory location between i and f holding data.i=20; got overwritten to a new value (220.5) with binary representation as follows :

再一次,当这个值被读取为一个有符号整数 int 时,它将被解释为十进制表示的 1130135552 而不进行转换.因此你得到 1130135552.

Now again, when this value is read as a signed integer int it will be interpreted without conversion as 1130135552 in decimal representation. Hence you are getting 1130135552.

此外,如果您想使用 union 的所有成员,那么 struct 就是答案.

Further if you want to use all members of union, then struct is the answer.

struct Data
{
    char str[20];
    int i;
    float f;
} data;

data.i=20;
data.f=220.5;
printf("%d\n",data.i);

有关unionstruct 的更多信息,请参阅

For more information on union and struct Please refer the following from Difference between Structure and Union:

这篇关于当其他成员设置为新值时,C 联合成员给出特定/错误的值.为什么这个输出在 C 中的以下代码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆