I was recently studying union and end up with a confusion even after reading a lot about it.
#include<stdio.h>
union test
{
int x;
char arr[4];
int y;
};
int main()
{
union test t;
t.x = 0;
t.arr[1] = 'G';
printf("%s\n", t.arr);
printf("%d\n",t.x);
return 0;
}
What I understood is :
Since x and arr[4] share the same memory, when we set x = 0, all characters of arr are set as 0. 0 is ASCII value of '\0'. When we do "t.arr[1] = 'G'", arr[] becomes "\0G\0\0". When we print a string using "%s", the printf function starts from the first character and keeps printing till it finds a \0. Since the first character itself is \0, nothing is printed.
What I don't get is second printf statement
Now since arr[] is "\0G\0\0" , the same location is shared with x and y.
So what I think x to be is the following
00000000 01000111 00000000 00000000 ("\0G\0\0")
so t.x should print 4653056.
But what it's printing is 18176.
Where am I going wrong?
Is this technically undefined or is it due to some silly mistake or am I missing some concept??