Structure Padding in C

Structure padding in C is the process of adding extra memory bytes between the members of a structure to align the data in memory for optimized access by the CPU. The padding is compiler-dependent and helps maintain data alignment according to the machine's architecture.

Why Structure Padding?

Example: Without Padding

This example demonstrates a structure without padding:

                        
#include <stdio.h>

#pragma pack(1) // Disable padding
struct NoPadding {
    char c;    // 1 byte
    int i;     // 4 bytes
};
        
int main() 
{
    struct NoPadding np;
    printf("Size of structure without padding: %zu bytes\n", sizeof(np));
        
    return 0;
}
                        
                    

Output:

Size of structure without padding: 5 bytes

Example: With Padding

By default, the compiler adds padding to align data members:

                        
#include <stdio.h>
        
struct WithPadding {
    char c;    // 1 byte
    int i;     // 4 bytes, starts at the 4th byte due to padding
};
        
int main()
{
    struct WithPadding wp;
    printf("Size of structure with padding: %zu bytes\n", sizeof(wp));
    return 0;
}
                        
                    

Output:

Size of structure with padding: 8 bytes

Explanation

Using #pragma pack()

You can use the #pragma pack directive to control padding:

                        
#include <stdio.h>
        
#pragma pack(1) // Disable padding
struct CustomPacking {
    char c;    // 1 byte
    int i;     // 4 bytes
};
        
int main() 
{
    struct CustomPacking cp;
    printf("Size of structure with custom packing: %zu bytes\n", sizeof(cp));
    return 0;
}
                        
                    

Output:

Size of structure with custom packing: 5 bytes

Key Points