Would this union work if char had stricter alignment requirements than int?
Posted
by
paxdiablo
on Stack Overflow
See other posts from Stack Overflow
or by paxdiablo
Published on 2010-12-21T05:23:55Z
Indexed on
2010/12/21
5:31 UTC
Read the original article
Hit count: 206
Recently I came across the following snippet, which is an attempt to ensure all bytes of i
(nad no more) are accessible as individual elements of c
:
union {
int i;
char c[sizeof(int)];
};
Now this seems a good idea, but I wonder if the standard allows for the case where the alignment requirements for char
are more restrictive than that for int
.
In other words, is it possible to have a four-byte int which is required to be aligned on a four-byte boundary with a one-byte char
(it is one byte, by definition, see below) required to be aligned on a sixteen-byte boundary?
And would this stuff up the use of the union above?
Two things to note.
I'm talking specifically about what the standard allows here, not what a sane implementor/architecture would provide.
I'm using the term "byte" in the ISO C sense, where it's the width of a
char
, not necessarily 8 bits.
© Stack Overflow or respective owner