关于VC中union的一个问题
来源:百度知道 编辑:UC知道 时间:2024/05/16 00:36:16
#include <stdio.h>
void main(){
union{
char pp;
float tt;
}hello;
union{
char pp2;
float tt2;
}hello2;
hello.tt=2.2323;
hello2.pp2=hello.pp;
printf("%f\n",hello2.tt2);
}
编译没有任何问题,但hello2.tt2的值压根和hello.tt不同
void main(){
union{
char pp;
float tt;
}hello;
union{
char pp2;
float tt2;
}hello2;
hello.tt=2.2323;
hello2.pp2=hello.pp;
printf("%f\n",hello2.tt2);
}
编译没有任何问题,但hello2.tt2的值压根和hello.tt不同
这个union里,char成员只占一个字节,float成员占4字节,也就是说,char成员只是float成员的1个低字节而已。你只写了hello.pp2=hello.pp,那么只是将这1个字节拷过来而已,其余3个字节仍是随机值,当然不一样了。
#include <stdio.h>
void main(){
union{
char pp;
char pp2;
}hello;
union{
float tt;
float tt2;
}hello2;
hello.tt=2.2323;
hello2.pp2=hello.pp;
printf(\"%f\\n\",hello2.tt2);
}