Search topics...
C / C++ ConceptsStructs, Unions, and Alignmentfoundational

Given this struct, what is sizeof(s) and why?

0 upvotes
Practice with AISoon
c
struct example {
uint8_t a; // 1 byte
uint32_t b; // 4 bytes
uint8_t c; // 1 byte
};

On a 32-bit ARM, sizeof(struct example) is 12 bytes, not 6. The compiler inserts 3 bytes of padding after a to align b on a 4-byte boundary, and 3 bytes of padding after c to make the struct's total size a multiple of its largest member's alignment (4 bytes).

Reordering the fields — uint32_t b; uint8_t a; uint8_t c; — reduces the size to 8 bytes (4 + 1 + 1 + 2 padding). In embedded systems with limited RAM, this reordering can save significant memory when thousands of structs are allocated. The rule: order fields from largest to smallest to minimize padding.

Source: C / C++ Concepts Q&A