Reputation: 1534
I have the structure
typedef struct EData
{
int a;
char c;
}
Edata obj;
a
is the integer variable so it takes 4 bytes and the c
is the char variable so it takes
1 byte, totalling 5 bytes
But when I print sizeof(obj)
it shows 8 bytes.
What is the reason?
Upvotes: 1
Views: 2234
Reputation: 54074
The increase in size you notice is due to compiler's padding.
Compiler adds extra bytes to enforce correct byte boundaries.
So compiler adds the extra bytes to enforce the proper location for each member according to its type.
There is an option to stop compiler to do this (packed directive) but it is best to avoid it (except in corner-cases)
Upvotes: 1
Reputation: 12861
If it's a problem for you, you can either use #pragma
or a compiler switch (a variety of compilers has such a switch).
Upvotes: 0
Reputation: 47592
Because on 32bit systems memory is aligned at 4byte (32bit)
boundaries so it has to multiple of 4bytes, see Data structure alignment
Upvotes: 4
Reputation: 138357
int
is 4 bytes, char
is 1 byte. However, your compiler aligns each struct
to a word (a word is 4 bytes on 32 bit architecture) as it improves performance. Therefore each instance of EData
will be rounded up to 2 words (or 8 bytes).
What you end up with is something like this:
typedef struct EData {
int a;
char c;
char padding[3];
}
Upvotes: 3