writes:
> On Aug 29, 2:18 am, Old Wolf <oldw...@inspire.net.nz> wrote:
> <snip>
>> However, the behaviour would be undefined if
>> arrayA is not correctly aligned for a struct mystruct.
>
> Could it ever happen that arrayA is not correctly aligned with struct
> mystruct, given the following:
> #define LEN 3
>
> struct mystruct {
> char arr[LEN];
> };
>
> char arrayA[LEN];
Yes. Note that compilers are likely to allocate objects on stricter
alignment boundaries than they really need to, so code that assumes
arrayA is strictly aligned may happen to work (until it breaks at the
most inconvenient possible moment).
> Might the struct have padding?
Yes.
> Would a union change the situation?
No.
> By the way - is a struct (or union) aligned according to its size, or
> according to the largest component it contains?
The alignment for a struct or union is at least the alignment for its
most strictly aligned member. It may be more strict. For any type,
the size must be a whole multiple of the alignment.
For example char always has one-byte alignment. An implementation
might require, say, 4-byte alignment for all structures. In that
case, this structure:
struct foo {
char c;
};
would have 4-byte alignment; it would therefore have to have at least
3 bytes of padding after 'c'. This is just one possibility; a
compiler is also free to set the size and alignment of 'struct foo' to
1 byte.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"