In a struct like
struct {
char word[10];
short a;
int b;
}
you have the following requirements:
a
needs an even offset. As the char arry before it has an even length, there is no need for padding. So a
sits at offset 10.
b
needs an offset which is dividible by 4. 12 is dividible by 4, so 12 is a fine offset for b
.
The whole struct needs a size which is dividible by 4, because every b
in an array of this struct needs to have the said requirement. But as we are currently at size 16, we don't need any padding.
WWWWWWWWWWAABBBB
|-- 10 --| 2 4 = 16
Compare this with
struct {
char word[11];
short a;
int b;
}
Here, a
would have offset 11. This is not allowed, thus padding is inserted. a
is fine with an offset of 12.
b
would then get an offset of 14, which isn't allowed either, so 2 bytes are added. b
gets an offset of 16. The whole struct gets a size of 20, which is fine for all subsequent items in an array.
WWWWWWWWWWW.AA..BBBB
|-- 11 --|1 2 2 4 = 20
Third example:
struct {
char word[11];
int b;
short a;
}
(note the changed order!)
b
is happy with an offset of 12 (it gets 1 padding byte),
a
is happy with an offset of 16. (no padding before it.)
After the struct, however, 2 bytes of padding are added so that the struct aligns with 4.
WWWWWWWWWW..BBBBAA..
|-- 10 --| 2 4 2 2 = 20