Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C union char array prints 'd' on mac?

Tags:

c++

c

I am new to C/C++, but was curious to know about the issue i am 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 is ...why is 'd' getting printed? I changed the order in union still the same output. but if i declare a char f[20] outside the union then nothing gets printed. I am having MacBook lion image and using xcode. THanks in advance

like image 423
Gana Avatar asked Jan 28 '26 21:01

Gana


1 Answers

The ASCII code for 'd' is 100. Setting a to 100 amounts to setting b to {'d', '\0', '\0', '\0', …noise…} (on a 32-bit little-endian machine), which printf treats as "d".

like image 177
Marcelo Cantos Avatar answered Jan 30 '26 17:01

Marcelo Cantos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!