开发者

UNION IN C (What will be the output)

union a
{
 int x;
 char a[2];
}
开发者_高级运维

If we assign 512 value to x and try to print a[0] and a[1] then what will be the output please explain how?


According to the standard, the result of writing to one member of a union, then reading from another isn't defined. Just about anything could happen.

Realistically, if you run the code on a little-endian machine, a[0] will probably be 0, and a[1] will probably be 2. On a 16-bit big-endian machine, a[0] would be 2 and a[1] would be 0. On a 32-bit big-endian machine, (the nonexistent, as you've defined things) a[2] would be 2, and a[0], a[1], &a[3] would be 0.


I the depends on the endianess of the platform. On little-endian platforms (Intel) a[0] will have the least significant byte of the integer (4 bytes), so a[0] will hold 0x00 and a[1] 0x02


It depends on the endian-ness of the computer you run it on:

union in effect uses the same memory for your int and your chars, so,

int           512 (ie 0x200)
char[4]       0x00 0x00 0x02 0x00  little endian, so a[0]=0, a[1]=0
char[4]       0x00 0x02 0x00 0x00  big endian   , so a[0]=0, a[1]=2

(actually, I might have little & big endian the wrong way around)


Unions in C share same memory space, that is, both x and a[2] start at the same memory location. When you assign the value to one of them, the other gets overwritten.

In your case, when you assign 512 to x, you'll write it's bytes to char as well, like Fernando Miguélez just explained...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜