C Structure Padding and Packing
Technically, the size of the structure in C should be the sum of the sizes of its members. But it may not be true for most cases. The reason for this is Structure Padding.
Structure padding is the concept of adding multiple empty bytes in the structure to naturally align the data members in the memory. It is done to minimize the CPU read cycles to retrieve different data members in the structure.
There are some situations where we need to pack the structure tightly by removing the empty bytes. In such cases, we use Structure Packing. C language provides two ways for structure packing:
- Using #pragma pack(1)
- Using __attribute((packed))__
Example of Structure Padding and Packing
C
// C program to illustrate structure padding and packing #include <stdio.h> // structure with padding struct str1 { char c; int i; }; struct str2 { char c; int i; } __attribute((packed)) __; // using structure packing // driver code int main() { printf ( "Size of str1: %d\n" , sizeof ( struct str1)); printf ( "Size of str2: %d\n" , sizeof ( struct str2)); return 0; } |
Size of str1: 8 Size of str2: 5
As we can see, the size of the structure is varied when structure packing is performed.
To know more about structure padding and packing, refer to this article – Structure Member Alignment, Padding and Data Packing.
C Structures
The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type.