Reputation: 411
I am using a structure, but unable to understand how the padding occurs. I am using a 64-bit system. The size of char is 1 byte, float is 4 byte and long is 8 byte in my system.
struct record{
char name[50];
float cost;
long num;
}stu;
Size: 64.
This result in size of: 64
struct record{
char name[50];
long num;
float cost;
}stu;
Size: 72.
I am not sure how padding takes place in both the cases.
Upvotes: 0
Views: 72
Reputation: 177461
Padding is used to maintain alignment of types. Processors tend to be more efficient if 4-byte types are aligned on addresses divisible by 4, for example.
struct record {
char name[50]; // offset 0 size 50 (type is size 1)
/* padding 2 bytes here */
float cost; // offset 52 (size 4, offset divisible by 4)
long num; // offset 56 (size 8, offset divisible by 8)
} stu; // total 64 (divisible by 8, (min of current packing size or largest member)
struct record {
char name[50]; // offset 0, size 50
/* padding 6 bytes here */
long num; // offset size 56, size 8, offset divisible by 8
float cost; // offset 64, size 4, offset divisible by 4
/* padding 4 bytes here */
} stu; // total 72, divisible by 8 (min of current packing size or largest member)
The trailing packing is needed in the case of contiguous arrays of structures to maintain natural alignment of types for each element of the array.
Upvotes: 1