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

The sizeof operator on structs

The sizeof operator on structs

What you'll learn: How to determine the memory footprint of a struct and why the result might be larger than the sum of its parts.

More than the sum of its parts

When you use the sizeof operator on a basic type like an int or a char, the result is predictable. However, when you apply sizeof to a struct, you might encounter a "C surprise." You might expect a struct containing a 4-byte integer and a 1-byte character to take up exactly 5 bytes. In reality, sizeof will often tell you it takes up 8 bytes.

Why the extra space? Think of memory like a parking lot with strictly painted lines. A motorcycle (a char) could fit anywhere, but a large SUV (an int) is only allowed to park in spots that start on a multiple of four. To keep everything lined up and easy for the CPU to find quickly, the compiler adds invisible "padding" bytes between or after your variables.

Seeing it in action

Because of this internal alignment, you should never try to "guess" the size of a struct by adding up the sizes of its members. Always use the sizeof operator to get the true footprint.

#include <stdio.h>

struct Box {
    char label;   // 1 byte
    int quantity; // 4 bytes
};

int main() {
    struct Box myBox;
    
    // You might expect 5, but you will likely see 8
    printf("Size of struct: %zu bytes\n", sizeof(myBox));
    
    return 0;
}

In the example above, the compiler inserts 3 bytes of empty padding after label so that quantity starts on a memory address that is a multiple of 4. This ensures the CPU can grab the integer in a single, efficient move.

Why this matters

The sizeof operator is your best friend when you need to allocate memory dynamically or write data to a file. It ensures that you are accounting for every byte, including the "hidden" padding the compiler added to keep the hardware happy. If you manually assumed the size was 5 bytes, you would accidentally cut off the end of your data!

Key takeaway

Always use sizeof to determine a struct's size, as compilers add invisible padding bytes to align data for faster CPU access.