K
Keith Thompson
Tim Rentsch said:Kenneth Brody said:Suppose you had this:
struct foo
{
char str[4];
int i;
}
c = { "abc" };
...
int *i = (int *)c.str;
Doesn't the standard guarantee that the struct be aligned in such a
way that c.str (the first struct element) must be properly aligned for
an int?
Yes, the alignment requirements for a struct are at least as
restrictive as the alignment requirements for each of the
members of the struct; this implication must hold because
of the guarantees made by malloc(). The alignment of the
first struct element matches the alignment of the struct,
as you point out.
I think it's true that the alignment requirements for a struct are at
least as restrictive as the alignment requirements for each of the
members, but this isn't implies by malloc(). A declared object
needn't be as strictly aligned as one allocated by malloc(). The
restriction follows from the requirements that all the members have to
be properly aligned, however the struct object itself was allocated.