c语言共用体问题

来源:百度知道 编辑:UC知道 时间:2024/06/07 04:32:11
main()
{
union dt
{int a;char b;double c;}data;
data.a=57;
printf("%d",data.c);
}

这个程序 用“%d”输出就是57
可是用“%f”输出却是0.000000
为什么?
在TC里int 型是占2个字节啊。

联合表示几个变量公用一个内存位置, 在不同的时间保存不同的数据类型和不同长度的变量。
union dt
{int a;char b;double c;}data;
int 占用4个字节,double占用8个字节,data.a=57只初始化了int型,double型未初始化,内存情况是未知的,所以输出情况是未定的。你用printf看,其实并看不到本质,你可以debug看看

下面是MSDN的引用:
If a union of two types is declared and one value is stored, but the union is accessed with the other type, the results are unreliable. For example, a union of float and int is declared. A float value is stored, but the program later accesses the value as an int. In such a situation, the value would depend on the internal storage of float values. The integer value would not be reliable.

int占几个字节并不重要,重要的是
1)union共用内存
2) char, int, double, float这些数据类型,占用的字节数是不一样的
3)访问未初始化的内存,结果是不可预知的

共用体中的所有成员共享一段公共的存储区,所以共用体所占内存字节数与其成员中字节数最多的那个成员相等,因此变量中的所有成员的首地址相同。
假如int 占用4个字节,double占用8个字节,data.a=57只初始化前4个字节,而当你用%d的格式输出时,系统会自动将data.c的前4字节解释为整数(其实就是data.a),而double或者float型因未完全初始化而且格式不同,当然就会出现意想不到的结果.

共用体中的所有成员共享一段公共的存储区,所以共用体所占内存