Course contentsShow
← C
Lesson 643 of 1,2199. Structures and UnionsFree lesson

Alignment requirements for different types

Alignment requirements for different types

What you'll learn: Why the CPU requires specific data types to be placed at specific memory addresses and how this influences structure layout.

The Post Office Analogy

Imagine a post office where the mail sorter can only grab four boxes at a time, but only if they start at a slot number divisible by four (0, 4, 8, etc.). If you place a large package across slots 3, 4, 5, and 6, the sorter has to make two separate trips to get your one item.

Computers work the same way. The CPU reads memory in "chunks" (usually 4 or 8 bytes). To keep performance fast, the hardware prefers that data starts at an address that matches its size. This is called alignment.

Common Alignment Rules

In C, every data type has an alignment requirement. While these can vary slightly between systems, the general rules are:

  • char (1 byte): Can start at any address (1-byte aligned).
  • short (2 bytes): Must start at an even address (2-byte aligned).
  • int and float (4 bytes): Must start at an address divisible by 4.
  • double or pointers (8 bytes): Usually must start at an address divisible by 8.

How it affects Structures

When you create a struct, the compiler ensures every member sits at a valid starting address. If a member doesn't fit the next available slot, the compiler leaves a gap. This gap is known as padding.

struct Example {
    char a;     // Address 0: Fits anywhere
    // 3 bytes of invisible "padding" added here!
    int b;      // Address 4: Must start on a multiple of 4
    char c;     // Address 8: Fits anywhere
    // 3 bytes of "padding" added at the end to keep the total size 12
};

In the example above, you might expect the struct to be 6 bytes (1 + 4 + 1). However, because of alignment, the compiler pads it out to 12 bytes. If int b started at address 1, the CPU would have to perform two memory reads to fetch one integer, significantly slowing down your program.

Why this matters

You don't usually have to manage alignment manually, but understanding it explains why sizeof(struct) is often larger than the sum of its parts. By ordering your struct members from largest to smallest, you can often minimize this wasted space.

Key takeaway

Alignment ensures the CPU can fetch data in a single efficient step by placing variables at memory addresses divisible by their size.