Confusion over align attribute

I understand that the align attribute has several different forms of use.

In my first attempt, I used it as follows:

 align(1) private struct TGAHeader { ubyte idLenght; ubyte hasColormap; ubyte imageType; ushort cmFirstEntry; ushort cmLength; ubyte cmSize; ushort xOrigin; ushort yOrigin; ushort width; ushort height; ubyte pixelDepth; ubyte imageDescriptor; } // TGAHeader.sizeof == 20 

This led to the structure being supplemented with two additional unwanted bytes.

After changing it:

 private struct TGAHeader { align(1): ubyte idLenght; ubyte hasColormap; ubyte imageType; ushort cmFirstEntry; ushort cmLength; ubyte cmSize; ushort xOrigin; ushort yOrigin; ushort width; ushort height; ubyte pixelDepth; ubyte imageDescriptor; } // TGAHeader.sizeof == 18 

I got the expected 18 bytes for the header size.

So, I doubt: what is the actual use of the first form of the align attribute if it doesn't seem to align the data, as you might expect?

+6
source share
1 answer

Quote from the link you provided:

Alignment of the aggregate fields does not affect the alignment of the aggregate itself - which is affected by the alignment setting outside the aggregate.

So, the second form aligns the structure fields. And the first aligns the structure.

In your example, consider a larger alignment - say, 16. The first form will lead to the following layout

 TGAHeader.sizeof = 32 // the padding was added in the end of the struct TGAHeader.idLenght.offsetof = 0 TGAHeader.hasColormap.offsetof = 1 TGAHeader.imageType.offsetof = 2 TGAHeader.cmFirstEntry.offsetof = 4 TGAHeader.cmLength.offsetof = 6 TGAHeader.cmSize.offsetof = 8 TGAHeader.xOrigin.offsetof = 10 TGAHeader.yOrigin.offsetof = 12 TGAHeader.width.offsetof = 14 TGAHeader.height.offsetof = 16 TGAHeader.pixelDepth.offsetof = 18 TGAHeader.imageDescriptor.offsetof = 19 

And the second form will result in

 TGAHeader.sizeof = 192 // every field was padded TGAHeader.idLenght.offsetof = 0 TGAHeader.hasColormap.offsetof = 16 TGAHeader.imageType.offsetof = 32 TGAHeader.cmFirstEntry.offsetof = 48 TGAHeader.cmLength.offsetof = 64 TGAHeader.cmSize.offsetof = 80 TGAHeader.xOrigin.offsetof = 96 TGAHeader.yOrigin.offsetof = 112 TGAHeader.width.offsetof = 128 TGAHeader.height.offsetof = 144 TGAHeader.pixelDepth.offsetof = 160 TGAHeader.imageDescriptor.offsetof = 176 
+7
source

Source: https://habr.com/ru/post/971320/


All Articles