Search⌘ K

Alignment: The .offsetof Property

Explore how the offsetof property in D programming helps identify the byte offset of members within structs, revealing memory alignment and padding. Understand how ordering members and using the align attribute affects struct size and performance, essential for effective memory management and optimization.

We'll cover the following...

The .offsetof property

Alignment is observed for members of user-defined types as well. There may be padding bytes between members so that the members are aligned according to their respective types. For that reason, the size of the following struct is not 6 bytes, as one might expect, but 12:

D
import std.stdio;
struct A {
byte b; // 1 byte
int i; // 4 bytes
ubyte u; // 1 byte
}
void main() {
writeln(A.sizeof == 12); // More than 1 + 4 + 1
}

This is due to padding bytes before the int member so that it is aligned at an address that is a multiple of 4, as well as padding bytes at the end for the alignment of the entire struct object.

The .offsetof ...