Frage

#include<stdio.h>
int main()
{
    union emp;
    union emp{
    int age;
    char name[2];
    };
    union emp e1={512};
    printf("%d,%d,%d",e1.age,e1.name[0],e1.name[1]);
    return 0;
}

Here ive tried to craete a union and initialize its 1st member i.e "int age". As per my knowledge ANSI C compilers support this. My question is why i am getting an output like "512,0,2". If i replace 512 with 513, 514 and 768 i get the following oytputs. "513,1,2", "514,2,2", "768,0,3", Now i can see that the e1.name[0] is storing (the number)%256 and e1.name[1] is storing (the number)/256. It would be greatly appreciated if it is explained that why and how this happens. Thank you all.

War es hilfreich?

Lösung

This is undefined behavior, you can't store a field in a union and retrieve it as another type. Thus, you can't really "expect" any output from this piece of code, because anything is acceptable as far as the standard is concerned.

See this question: A question about union in C

Apart from that, since 512 is 2^9, assuming integers are 32 bits and chars are 8 bits, this just means that your architecture is little endian, because 512 is 0x200. When you access e1.name[0] and e2.name[1], you are accessing the first 2 bytes of 512 that were stored in memory, which apparently happens to be 0x00 (the least significant byte), and 0x2 (next byte after the least significant).

Andere Tipps

That's what a union is supposed to do. It stores the same data in different data types. For your values

513 = 0x0201
514 = 0x0202
768 = 0x0300

name[0] is storing the least significant byte and and name[1] is storing the most significant byte. If you were using a different architecture it would be reversed.

Imagine that: a union can hold two chars OR one int. If you store an int to the union, the two char part can be read out as well, but they will contain the binary part of the stored int. So in your example, name[0] will contain the lower 16 bits of the originally stored int, name[1] will contain the upper 16 bits of the original int.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top