Course contentsShow
← C
Lesson 948 of 1,21913. Advanced CFree lesson

The `#pragma pack` directive

The #pragma pack directive

What you'll learn: How to disable automatic memory padding to control the exact byte-by-byte layout of your structures.

The Gap in Your Data

Computers like efficiency. When you define a struct, the compiler often inserts invisible "padding" bytes between members. For example, if you have a 1-byte char followed by a 4-byte int, the compiler might add 3 empty bytes after the char so the int starts at a memory address divisible by 4. This is called alignment, and it helps the CPU read data faster.

However, sometimes you need to talk to hardware or read a specific file format where those extra "gap" bytes aren't allowed. This is where #pragma pack comes in.

Tightening the Belt

Think of your struct like a suitcase. By default, the airline (the compiler) leaves spaces between items so they don't get squashed. Using #pragma pack is like vacuum-sealing your clothes: you remove all the air to make everything fit in a specific, tight order.

#include <stdio.h>

// Tell the compiler to stop adding padding (align to 1 byte)
#pragma pack(push, 1) 
struct CompressedData {
    char status;    // 1 byte
    int sensorValue; // 4 bytes
};
#pragma pack(pop) // Restore original alignment settings

int main() {
    // Without packing, this would likely be 8 bytes
    // With packing, it is exactly 5 bytes
    printf("Size of struct: %zu bytes\n", sizeof(struct CompressedData));
    return 0;
}

How it Works

  1. push, 1: The push command saves your current alignment settings, and 1 tells the compiler to pack members as tightly as possible (no gaps larger than 1 byte).
  2. The Struct: Inside the "packed" zone, every member follows the previous one immediately.
  3. pop: This restores the compiler's default behavior. It is vital to pop your settings so you don't accidentally slow down the rest of your program.

Why Use It?

You will mostly use this for Portability. If you send a struct over a network from a 64-bit machine to a 32-bit microcontroller, they might assume different padding rules. By forcing #pragma pack(1), you guarantee that both devices see the exact same byte sequence. Just be careful: while packing saves space, it can make the CPU work a little harder to read the data.

Key takeaway

Use #pragma pack(1) to remove invisible padding bytes when your struct must match a specific external data format or hardware register.