我有一些关于联合使用的代码,如下所示:
int main(){
typedef union{int a;char b[10];float c;}Union;
Union x,y = {100};
printf("Union x :%d| |%s| |%f \n",x.a,x.b,x.c );
printf("Union y :%d| |%s| |%f \n\n",y.a,y.b,y.c);
x.a = 50;
printf("Union x :%d| |%s| |%f \n",x.a,x.b,x.c );
printf("Union y :%d| |%s| |%f \n\n",y.a,y.b,y.c);
strcpy(x.b,"hello");
printf("Union x :%d| |%s| |%f \n",x.a,x.b,x.c );
printf("Union y :%d| |%s| |%f \n\n",y.a,y.b,y.c);
x.c = 21.50;
printf("Union x :%d| |%s| |%f \n",x.a,x.b,x.c );
printf("Union y :%d| |%s| |%f \n\n",y.a,y.b,y.c);
return 0;
}
在我编译并执行上面的代码后,我得到了这样的结果:
Union x :0| || |0.000000
Union y :100| |d| |0.000000
Union x :50| |2| |0.000000
Union y :100| |d| |0.000000
Union x :1819043176| |hello| |1143141483620823940762435584.000000
Union y :100| |d| |0.000000
Union x :1101791232| || |21.500000
Union y :100| |d| |0.000000
不知道为什么yb被初始化为“d”?为什么 xa 和 xc 的值在之后发生了变化?为什么 strcpy(xb,"hello") 不起作用?