What is structure padding in C?
The compiler adds empty bytes (padding) between structure members so that each member starts at an address that suits its type. So the size of a structure can be more than the sum of its members.
#include <stdio.h>
struct A { char a; int b; char c; };
struct B { int b; char a; char c; };
int main(void) {
printf("%zu\n", sizeof(struct A));
printf("%zu\n", sizeof(struct B));
return 0;
}
Output:
Output of the above program is
12
8
Both have the same members, but the order in struct B wastes less space. A good habit is to put the bigger members first.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |