Open In App

How to Pack a Struct in C?

In C, when you declare a structure, the compiler allocates memory for its members, and the way it does this can involve adding padding between members for alignment purposes. struct packing refers to the arrangement of the members of a structure in memory so that there is no extra space left. In this article, we are going to learn how to pack a structure in C.

Example



Input:
Size of Struct myStruct = 16 bytes

Output:
// after packing
Size of Struct myStuct = 12 bytes

Pack a Struct in C

We can pack a struct by using the #pragma directive with the pack argument. This overrides the default packing scheme and can make the packing scheme of the structure as defined. To tightly pack the structure, we can use the directive #pragma pack(1).

C++ Program to Pack a Struct




// C++ Program to show how to Pack a Struct
#include <stdio.h>
  
// Pack struct members on 1-byte boundaries
#pragma pack(1)
  
struct PackedStruct {
    char a; // 1 byte
    int b; // 4 bytes
    double c; // 8 bytes
};
  
int main()
{
    printf("Size of PackedStruct: %zu bytes\n",
           sizeof(struct PackedStruct));
    return 0;
}

Output

Size of PackedStruct: 13 bytes
Article Tags :