Reputation: 1805
I read the following code from wikipedia
struct MixedData
{
char Data1;
short Data2;
int Data3;
char Data4;
}md;
printf("%u %u %u %u", &md.Data1, &md.Data2, &md.Data3, &md.Data4);
The output is:-
268624 268626 268628 268632
I am unable to understand how padding is applied after each data member in the above code?
Upvotes: 2
Views: 142
Reputation: 2373
From here
first element is char which is one byte aligned, followed by short int. short int is 2 byte aligned. If the the short int element is immediately allocated after the char element, it will start at an odd address boundary. The compiler will insert a padding byte after the char to ensure short int will have an address multiple of 2 (i.e. 2 byte aligned).
This is how your struct looks like:
+-------+-------+-------+-------+
| Data1 | | Data2 |
+-------+-------+-------+-------+
| Data3 |
+-------+-------+-------+-------+
| Data4 | | | |
+-------+-------+-------+-------+
So padding from char to short
is one byte =>
268624 to 268625 is Data1, from 268625 to 268626 padding to short
.
then 268626 to 268628 short
no padding needed, all aligned to max type of the struct.
From the same reference
There is a way to minimize padding. The programmer should declare the structure members in their increasing/decreasing order of size
The way to improve your struct is to place char Data4;
directly after char Data1;
This way no memory will be wasted for padding:
struct MixedData
{
char Data1;
char Data4;
short Data2;
int Data3;
}md;
printf("%p %p %p %p", &md.Data1,&md.Data4, &md.Data2, &md.Data3);
0x602270 0x602271 0x602272 0x602274
The basic assumption, that compiler is stick with natural alignment of int on x86
Upvotes: 1
Reputation: 22241
How?
2 bytes for 1 byte char
2 bytes for 2 byte short
4 bytes for 4 byte int
? bytes for 1 byte char
The real question is: why?
And the answer to that question is here, structure padding and packing and here, sizeof != sum (fields)
Upvotes: 0