I have some code which is about the usage of union shown as following:
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;
}
After I compile and execute above code, I had result like this:
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
I do not know why the y.b is initialized as "d"? and why x.a and x.c's value changed after? why does the strcpy(x.b,"hello") not work?