c++ - C union char array prints 'd' on mac? -


i new c/c++, curious know issue seeing.

typedef union {    int a;    float c;    char b[20]; } union;  int main() {  union y = {100};  printf("union y :%d - %s - %f \n",y.a,y.b,y.c); } 

and output is

 union y :100 - d - 0.000000 

my question ...why 'd' getting printed? changed order in union still same output. if declare char f[20] outside union nothing gets printed. having macbook lion image , using xcode. in advance

i changed order in union still same output.

the order of elements in union doesn't change because elements of union use same piece of memory. code prints 100 y.a , d y.b because both expressions interpret same bytes. so, example, if add line sets y.b , prints again:

union y = {100}; printf("union y :%d - %s - %f \n",y.a,y.b,y.c); y.b = 'f'; printf("union y :%d - %s - %f \n",y.a,y.b,y.c); 

you'll see y.a , y.c. change whenever y.b changes, , vice versa. y.a should change 102 in second printf(), since that's ascii character code 'f'.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -