For example, there is a structure
struct A
{
char a;
int i;
};
In this case, we have a[1 byte] + padding[3 byte] + int[4 byte] = 8.
Now let's make little update into struct above,
struct A
{
int i;
char a;
};
In this case char comes after int and no need to add padding bytes, it means sizeof(A) = 5 byte, but in this case I also get the 8 byte result. Why ?
Ok, and what about this case
struct s
{
int b;
double c;
char a;
};
According logic given below, there is a: size = b[4 bytes] + padding[4 bytes] + c[8] + a[1] + padding[7 bytes to align with double] = 24
,
but after execution I get 16. How this is possible ?
Not only each member of the
struct
has to be data aligned, but thestruct
itself has to aligned to the size of the largest member in thestruct
. So, padding is added tostruct A
such that its size should be a multiple of the larger ofsizeof i
andsizeof a
.Have a look at C FAQ here
First you need to understand why padding is needed?
Wiki says that:
To make the size multiple of
4
(alignment ofint
) , the second snippet will be padded with3
bytes. After compilation the second snippet will be padded for proper alignment asEDIT: Always remember the two golden rules of structure padding:
In case of
alignment will take place as
Also note that by changing the ordering of members in a structure, it is possible to change the amount of padding required to maintain alignment. This can be done by if members are sorted by descending alignment requirements.
If one is going to have an array of structures, all elements within the array must have the same size and alignment; this would imply that for things in an array the size must be a multiple of alignment. The only time it would be useful to have a structure whose size was not a multiple of alignment would be if it was not incorporated directly into another array, but was instead used as part of another structure. That kind of situation does occur sometimes, but not sufficiently often as to merit special attention in the language design.
The reason the compiler have to add padding at the end of your struct is that the struct can be part of an array, and each element of an array must be properly aligned.
It seems your platform wants an int to be aligned to 4 bytes.
If you declare an array of your
struct A
:Then the first
int
member ofarray[1]
should also have an alignment of 4 bytes. So the compiler pads yourstruct A
to be 8 bytes to accomplish that, whilst if it didn't add any padding andsizeof(struct A)
were 5 bytes,array[1]
would not be properly aligned.(Keep in mind that a compiler can't insert padding inbetween array elements, padding have to be part of the array elements themselves since
sizeof array
must be the same assizeof(struct A) * 2
in the above case)