How to Pack a Struct in C?
Last Updated :
28 Feb, 2024
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
#include <stdio.h>
#pragma pack(1)
struct PackedStruct {
char a;
int b;
double c;
};
int main()
{
printf ( "Size of PackedStruct: %zu bytes\n" ,
sizeof ( struct PackedStruct));
return 0;
}
|
Output
Size of PackedStruct: 13 bytes
Share your thoughts in the comments
Please Login to comment...