I understand by data alignment concept that int's and floats's should be stored at address which is divisible by 4 (the starting byte address) .According to it, the size of the below structure is 12
typedef struct{
char A;
int B;
float C;
}y;
I have no doubt in understanding the size of above structure Now my doubt is about the size of below structure
typedef struct {
double A;
char B;
char C;
}x;
the size of x is 16. what my doubt is that the two characters used can be allocated in 2 bytes such that a whole structure uses 10 bytes of data and the remaining 2 bytes can be used to allocate to another short int when it was declared right?
But the compiler uses 16 bytes of data and pads the other 6 cells. I can't understand why it is wasting another 6 cells if it can use them for another variables when they are declared?. Can anyone please help me in understanding the above concept?.(I am assuming the size of int ,float and double as 4,4,8 bytes respectively. )
In the case of x
, it contains a double
which (in your case) has size 8. That means that the structure as a whole needs to be a multiple of that size in order for an array of x
to be properly aligned.
Since arrays are contiguously allocated, each member of the array comes immediately after the prior one in memory. If x
had size 10, then for an array the second element would have the A
member at offset 10. For proper alignment, each array member needs to start at a multiple of the size of the largest element. So the structure contains padding at the end to accomplish this.