Prerequisites: Structure Member Alignment, Padding and Data Packing
In Structure, sometimes the size of the structure is more than the size of all structures members because of structure padding.
Below is an example of Structure padding:
// C program to show an example // of Structure padding #include <stdio.h> struct s { int i; char ch; double d; }; int main() { struct s A; printf("Size of A is: %ld", sizeof(A)); } |
Size of A is: 16
Note: But what actual size of all structure member is 13 Bytes. So here total 3 bytes are wasted.
So, to avoid structure padding we can use pragma pack as well as an attribute.
Below are the solutions to avoid structure padding:
Program-1: Using pragma pack
// C program to avoid structure // padding using pragma pack #include <stdio.h> // To force compiler to use 1 byte packaging #pragma pack(1) struct s { int i; char ch; double d; }; int main() { struct s A; printf("Size of A is: %ld", sizeof(A)); } |
Size of A is: 13
Program-2: Using attribute
// C program to avoid structure // padding using attribute #include <stdio.h> struct s { int i; char ch; double d; } __attribute__((packed)); // Attribute informing compiler to pack all members int main() { struct s A; printf("Size of A is: %ld", sizeof(A)); } |
Size of A is: 13
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Structure Member Alignment, Padding and Data Packing
- What are Wild Pointers? How can we avoid?
- What is Memory Leak? How can we avoid?
- C | Structure & Union | Question 10
- C | Structure & Union | Question 9
- C | Structure & Union | Question 8
- C | Structure & Union | Question 7
- C | Structure & Union | Question 6
- C | Structure & Union | Question 4
- C | Structure & Union | Question 10
- C | Structure & Union | Question 2
- C | Structure & Union | Question 1
- Difference between Structure and Union in C
- Anonymous Union and Structure in C
- C | Structure & Union | Question 5
- Difference between Structure and Array in C
- C | Loops & Control Structure | Question 21
- Read/Write structure to a file in C
- C | Loops & Control Structure | Question 18
- C | Loops & Control Structure | Question 19
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

