Changing order of the variables In C Language
Categories: C language
#include <stdio.h>
struct student
{
char a;
int b;
char c;
};
int main()
{
struct student stud1; // variable declaration of the student type..
// Displaying the size of the structure student.
printf("The size of the student structure is %d", sizeof(stud1));
return 0;
}
The above code is similar to the previous code; the only thing we change is the order of the variables inside the structure student. Due to the change in the order, the output would be different in both the cases. In the previous case, the output was 8 bytes, but in this case, the output is 12 bytes, as we can observe in the below screenshot.
How to avoid the structure padding in C?
The structural padding is an in-built process that is automatically done by the compiler. Sometimes it required to avoid the structure padding in C as it makes the size of the structure greater than the size of the structure members.
We can avoid the structure padding in C in two ways:
1. Using #pragma pack(1) directive
2. Using attribute
Using #pragma pack(1) directive
#include <stdio.h>
#pragma pack(1)
struct base
{
int a;
char b;
double c;
};
int main()
{
struct base var; // variable declaration of type base
// Displaying the size of the structure base
printf("The size of the var is : %d", sizeof(var));
return 0;
}
In the above code, we have used the #pragma pack(1) directive to avoid the structure padding. If we do not use this directive, then the output of the above program would be 16 bytes. But the actual size of the structure members is 13 bytes, so 3 bytes are wasted. To avoid the wastage of memory, we use the #pragma pack(1) directive to provide the 1-byte packaging.