Is there guarantee, that memory for this object will be properly aligned if we create object of this type in stack?
union my_union
{
int开发者_C百科 value;
char bytes[4];
};
If we create char bytes[4] in stack and then try to cast it to integer there might be alignment problem. We can avoid that problem by creating it in heap, however, is there such guarantee for union objects? Logically there should be, but I would like to confirm.
Thanks.
Well, that depends on what you mean.
If you mean:
Will both the
int
andchar[4]
members of the union be properly aligned so that I may use them independently of each other?
Then yes. If you mean:
Will the
int
andchar[4]
members be guaranteed to be aligned to take up the same amount of space, so that I may access individual bytes of theint
through thechar[4]
?
Then no. This is because sizeof(int)
is not guaranteed to be 4. If int
s are 2 bytes, then who knows which two char
elements will correspond to the int
in your union
(the standard doesn't specify)?
If you want to use a union to access the individual bytes of an int
, use this:
union {
int i;
char c[sizeof(int)];
};
Since each member is the same size, they're guaranteed to occupy the same space. This is what I believe you want to know about, and I hope I've answered it.
Yeah, unions would be utterly useless otherwise.
精彩评论