As per my knowledge, By default 4-byte alignment will be done. say
typedef struct
{
int data7;
unsigned char data8;
//3 -bytes will be added
data7
is a 4-byte item, so the compiler will normally attempt to align it to an address that's a multiple of 4.
data1
is a one-byte item, so the compiler won't try to align it to any particular boundary (i.e., there would be no real gain from doing so).
None of the fields in your second struct require 4-byte alignment. unsigned char
only needs 1-byte alignment. Therefore, there is no need to actually align it to 4 bytes.
Structs are generally only aligned to the maximum alignment of all the fields.
Char requires 1 byte alignment. The max data type there is char , which is one byte alignment hence you are getting the size as '6'.
You can check this site for more understanding. http://www.geeksforgeeks.org/archives/9705. They have explained it in detail.
No, in a typical implementation Sample2
is not a 4-bute aligned structure. It is a 1-byte aligned structure.
In a typical implementation, the alignment requirement of the whole structure is calculated as the maximum of the alignment requirement of its individual members. This is why your Sample1
has alignment requirement of int
(4 on your platform), and your Sample2
has alignment requirement of unsigned char
, which is 1.