Consider:
struct mystruct_A
{
char a;
int b;
char c;
} x;
struct mystruct_B
{
int b;
char a;
} y;
The sizes of the structur
Rules for padding:
Why Rule 2: Consider the following struct,
If we were to create an array(of 2 structs) of this struct, No padding will be required at the end:
Therefore, size of struct = 8 bytes
Assume we were to create another struct as below:
If we were to create an array of this struct, there are 2 possibilities, of the number of bytes of padding required at the end.
A. If we add 3 bytes at the end and align it for int and not Long:
B. If we add 7 bytes at the end and align it for Long:
The start address of the second array is a multiple of 8(i.e 24). The size of the struct = 24 bytes
Therefore, by aligning the start address of the next array of the struct to a multiple of the largest member(i.e if we were to create an array of this struct, the first address of the second array must start at an address which is a multiple of the largest member of the struct. Here it is, 24(3 * 8)), we can calculate the number of padding bytes required at the end.