When I print the size of a union like this:
union u {
char c[5];
int i;
} un;
using this:
int _tmain(int argc, _TCHAR*
The sizeof
operator produces the size of a variable or type, including any padding necessary to separate elements in an array of that type such that everything is still correctly aligned. Since your union has an int
member, it needs to be 4-byte aligned, so its "natural" size gets rounded upwards to the next multiple of 4 bytes.
The ffffff98
is because you're compiling with signed char
. Using %x
with an argument that is not unsigned int
causes undefined behaviour; what you're seeing is sometimes called sign-extension. The result of your aliasing is 0x98
reinterpreted as char
, which is -104
. This retains its value on being promoted to int
(this is called the default argument promotions), and the int -104
when aliased as unsigned int
becomes 0xffffff98
.