In a struct, the padded bytes depend on the alignment requirement of the next member following the current member, because the compiler must ensure proper and efficient access to memory.

  1. Alignment Requirement: Each data type has a required alignment, which is typically a power of two. For example:

    • char: 1-byte alignment
    • int: 4-byte alignment
    • long (on a 64-bit system): 8-byte alignment
    • double: 8-byte alignment
  2. Padding: When laying out struct members, if the next member needs stricter (i.e. larger) alignment than the current offset provides, the compiler inserts padding bytes. This ensures that each member begins at an address meeting its required alignment.

  3. Struct Size: The size of the struct is also rounded up to match the largest alignment requirement within the struct.

Example

struct WithoutInt {
    char a;     // 1-byte aligned
    // int b;     // 4-byte aligned
    double c;   // 8-byte aligned
};

//[a][padding][padding][padding][padding][padding][padding][padding][c........]
// ^0 bytes, ^1 to 7 bytes of padding...                          , ^8 to 15 bytes for double c

struct WithInt {
    char a;     // 1-byte aligned
    int b;      // 4-byte aligned
    double c;   // 8-byte aligned
};

[a][padding][padding][padding][b...........][c......................]
 ^ 0 byte, ^1-3 bytes padding, ^4-7 bytes b, ^8-15 bytes c


std::cout << sizeof(WithoutInt) << std::endl; // 16 bytes
std::cout << sizeof(WithInt) << std::endl; // 16 bytes