If you've got a struct within a struct, say:
struct {
double a;
struct {
char *b[20];
char c;
}d;
}e;
will struct e need to start on a multiple of the size of struct d, or a multiple of the size of the largest member of d (char *b[20])?
The struct e
will start at whatever alignment is necessary for the members, and the struct as a whole, to be accessible.
That alignment will vary for different implementations.
We know that the alignment for e
will be at least as strict as the alignmentf for double
and at least as strict as the alignment for e.d
-- and the alignment of e.d
will be at least as strict as the alignment for its members.
Contrary to the other answers, the alignment of a scalar type is not necessarily the same as its size. For example, it's possible that double
might be 8 bytes, but only require 4-byte alignment. Aligning each scalar type (integer, floating-point, pointer) to its full size is fairly common, but it's not universal.
And note that the optimal alignment may be more strict than the required alignment. On the x86, as I understand it, the CPU can access objects on any byte boundary -- but access to properly aligned objects is more efficient. (On other CPUs, misaligned access may require software support.) Compilers will typically align objects for maximum efficiency (but may provide non-standard extensions to save space).
But the alignment for a type cannot exceed its size. For example, you can't have a 3-byte type that requires 4-byte alignment. Arrays cannot have gaps between their elements. (In such a case, the compiler would probably pad the type to 4 bytes; the padding would be part of the object, not inserted between objects.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With