Course contentsShow
← C
Lesson 453 of 1,2197. PointersFree lesson

Determining variable alignment in memory

Determining variable alignment in memory

What you'll learn: How to use the _Alignof operator to discover the memory alignment requirements of different data types.

The library shelf analogy

Imagine a library where the shelves are divided into 4-inch sections. If you have a thin magazine, it fits anywhere. But if you have a massive encyclopedia, the librarian insists it starts exactly at the beginning of a new section to keep the shelf balanced and easy to search.

Computer memory works similarly. For the CPU to read data efficiently, it doesn't just toss variables anywhere. It aligns them. An int might need to start at an address divisible by 4, while a char (the thin magazine) can start anywhere. This "divisibility rule" is called alignment.

Meet the _Alignof operator

In C, you don't have to guess these rules. The _Alignof operator (introduced in C11) tells you the "alignment requirement" of any type. It returns a number representing the power of two (1, 2, 4, 8, etc.) that the variable's memory address must be a multiple of.

Here is how you check these requirements in code:

#include <stdio.h>
#include <stdalign.h> // Required for the 'alignof' macro

int main() {
    // We use %zu because alignment values are of type size_t
    printf("Alignment of char: %zu byte\n", alignof(char));
    printf("Alignment of int:  %zu bytes\n", alignof(int));
    printf("Alignment of double: %zu bytes\n", alignof(double));

    return 0;
}

Note: While the keyword is _Alignof, including <stdalign.h> allows you to use the cleaner, lowercase alignof.

Why does this matter?

If an int has an alignment of 4, the computer will only place it at addresses like 1000, 1004, or 1008. It will never place it at 1001.

Understanding this is the "secret ingredient" to understanding pointers. A pointer isn't just a random number; it is an address that must respect these alignment boundaries. If you try to force a variable into a "misaligned" address, the CPU has to work twice as hard to read it, or in some cases, the program will simply crash. By knowing the alignment, you understand the invisible grid that your pointers are stepping across.

Key takeaway

Alignment is a restriction that forces variables to start at memory addresses divisible by specific values to ensure hardware efficiency.