struct {
integer a;
struct c b;
...
}
In general how does gcc calculate the required space? Is there anyone here who has ever peeked into the internals?
I have not "peeked at the internals", but it's pretty clear, and any sane compiler will do it exactly the same way. The process goes like:
Here's an example (assume int
is 4 bytes and has 4 byte alignment):
struct foo {
char a;
int b;
char c;
};
char
(1); size is still 0.char
(1); size is now 1.int
(4); size is now 4.int
(4); size is now 8.char
(1); size is still 8.char
(1); size is now 9.Edit: To address why the last step is necessary, suppose instead the size were just 9, not 12. Now declare struct foo myfoo[2];
and consider &myfoo[1].b
, which is 13 bytes past the beginning of myfoo
and 9 bytes past &myfoo[0].b
. This means it's impossible for both myfoo[0].b
and myfoo[1].b
to be aligned to their required alignment (4).
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