Reputation: 4585
typedef struct structA
{
char C;
double D;
int I;
} structA_t;
Size of this structA_t structure:
sizeof(char) + 7 byte padding + sizeof(double) + sizeof(int) = 1 + 7 + 8 + 4 = 20 bytes
But this is wrong , the correct is
24
. Why?
Upvotes: 1
Views: 218
Reputation: 3500
Good article on padding/alignment: http://www.drdobbs.com/cpp/padding-and-rearranging-structure-member/240007649
Because of the double member it forces everything to be eight byte aligned.
If you want a smaller structure then following structure gives you 16 bytes only!
typedef struct structA
{
int I;
char C;
double D;
} structA_t;
Upvotes: 0
Reputation: 16043
There is most likely 4 byte padding after the last ìnt
.
If sizeof(double) == 8
then likely alignof(double) == 8
also on your platform.
Consider this situation:
structA_t array[2];
If size would be only 20, then array[1].D
would be misaligned (address would be divisible by 4, not 8 which is required alignment).
Upvotes: 2
Reputation: 949
char = 1 byte
double = 8 bytes
int = 4 bytes
align to double =>
padding char => 1+7
padding double => 8+0
padding int => 4+4
=> 24 bytes
or, simply put, is the multiple of the largest => 3 (the number of fields) * 8 (the size of the largest) = 24
Upvotes: 1
Reputation: 1271
my guess would be the size of int
in your system is 4 Bytes, so the int must also be padded by 4 Bytes in order to achieve a word size of 8 Bytes.
total_size=sizeof(char) + 7 Byte padding + sizeof(double) + sizeof(int) + 4 Bytes padding = 24 Bytes
Upvotes: 0