Reputation: 13
typedef struct structc_tag
{
char c;
double d;
int s;
} structc_t;
Applying same analysis, structc_t needs sizeof(char) + 7 byte padding + sizeof(double) + sizeof(int) = 1 + 7 + 8 + 4 = 20 bytes but the sizeof(structc_t) will be 24 bytes.I didn't understood the alignment.Any one can help me?
Upvotes: 1
Views: 477
Reputation: 249642
Your struct looks like this, if we write it all out:
typedef struct structc_tag
{
char c;
char pad1[7];
double d;
int s;
char pad2[4];
} structc_t;
The pad2
is what you don't want. It comes into play because the compiler assumes you may want to make an array of these things, in which case every d
has to be aligned, so sizeof(structc_t)
is 24.
You can enable struct packing using a compiler-specific extension like this:
typedef struct structc_tag
{
char c;
char pad1[7];
double d;
int s;
} __attribute__((packed)) structc_t;
Now pad1
is needed (otherwise d
will immediately follow c
which you don't want). And pad2
is no longer implicitly added, so the size should now be 20.
Upvotes: 1