Packing of Struct Fields

ag0aep6g anonymous at example.com
Fri Oct 16 20:44:37 UTC 2020


On 16.10.20 22:32, Per Nordlöw wrote:
> Why is `T.sizeof` 12 instead of 8 when `U.sizeof` is 8 in the following 
> example?
> 
> struct S
> {
>      int i;
>      bool b;
> }
> 
> struct T
> {
>      S s;
>      char c;
> }
> 
> struct U
> {
>      int i;
>      bool b;
>      char c;
> }
> 
> ?

S.sizeof: 4 bytes for the int + 1 byte for the bool + 3 bytes padding so 
that the int is aligned = 8 bytes.

T.sizeof: 8 bytes for the S + 1 byte for the char + 3 bytes padding so 
that the S is aligned = 12 bytes.

U.sizeof: 4 bytes for the int + 1 byte for the bool + 1 byte for the 
char + 2 bytes padding so that the int is aligned = 8 bytes.


More information about the Digitalmars-d-learn mailing list