Packing of Struct Fields

Steven Schveighoffer schveiguy at gmail.com
Fri Oct 16 21:26:12 UTC 2020


On 10/16/20 4:44 PM, ag0aep6g wrote:
> 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.

To further explain this -- the padding is added so things like pointer 
arithmetic on an array work.

For example, if you have a T* t, and you say t += 1, you want it to go 
to the next T, not to a misaligned spot.

You can also override this with align keyword. But I don't recommended 
this unless you know what you are doing. Misaligned reads/writes are 
different on different architectures, but even if they work and don't 
crash your program, they are going to be slower.

https://dlang.org/spec/attribute.html#align

-Steve


More information about the Digitalmars-d-learn mailing list