In this tutorial we shall learn about structure padding.
We shall learn below topics:
What is structure padding?
How to avoid structure padding?
How to avoid structure padding using a macro?
1. What is structure padding?
Padding is a concept to add more bytes to structure or class, so that the accessing will be easier.
We shall understand it with the help of an example.
In the below example, we have a 2 character variable and a integer variable. According to our calculation, the space should be 4 bytes for 2 char variable, 4 bytes for 1 int variable. We shall execute the program and check.
#include <iostream>
using namespace std;
struct MyStruct
{
char c1;
int num;
char c;
};
int main(void)
{
MyStruct obj;
cout<<"size is "<<sizeof(obj);
return 0;
}
Output:
size is 12
As you can see, the char variable has also taken 4 bytes. And hence the total size is 4 + 4 + 4 = 12 bytes.
This is called as structure padding. Compiler does this optimization, so it will be efficient to read and write into the memory.
2. How to avoid structure padding?
To avoid structure padding, you need to put all the data type with higher memory in the beginning and lower data type at the end.
#include <iostream>
using namespace std;
struct MyStruct
{
int num;
char c1;
char c;
};
int main(void)
{
MyStruct obj;
cout<<"size is "<<sizeof(obj);
return 0;
}
Output:
size is 8
Now you can see that the size is reduced to 8.
3. How to avoid structure padding using a macro?
You can also avoid structure padding by adding a macro “#pragma pack (1)”.
#include <iostream>
using namespace std;
#pragma pack (1)
struct MyStruct
{
char c1;
int num;
char c;
};
int main(void)
{
MyStruct obj;
cout<<"size is "<<sizeof(obj);
return 0;
}
Output:
size is 6