struct total size does not match the sum of the components
Hello,
I usually develop in C for embedded platform (mplab C18 from microchip) and I use very often struct.
I began to work on a project on a PC and I encounter one weird behavior which I don't understand :
1st, when I do the sizeof(short, long, int and char) I get :
short : 2 bytes
long : 8 bytes
int : 4 bytes
char : 1 byte
In the following struct, the total size from (sizeof) is 6 but if I do the sum of the size of the differents elements, it should sum 5.
Code:
typedef struct _test
{
unsigned char a;
unsigned short b; // 2 bytes
unsigned char c : 4;
unsigned char d : 4;
unsigned char e : 2;
unsigned char f : 6;
}test;
so:
a = 1 byte
b = 2 bytes
c + d = 1 byte
e + f = 1 byte
Why do the compiler add an empty byte somewhere ? At first, I though it was because the structs must be 2 bytes aligned but the following struct works fine :
Code:
typedef struct _test2
{
unsigned char a;
unsigned char b;
unsigned char c;
}test2;
the sizeof gives me 3 bytes which is right.
If I only put 1 short in the structure, the structure is sized 2 bytes. but if I add an unsigned char, the size is not right (4 bytes)...
I can't understand whis this behavior and How to bypass this ?
Thank you for your help !