I was looking at several SO posts on bit fields like link1 link2. I am using TDM-GCC-64 compiler. In wrote this code below to test the size of structures under various scenario.
#include <stdio.h>
struct P
{
int k:2;
char c:1;
};
struct Q
{
int k:2;
short c:1;
};
#pragma pack(1)
struct R
{
int k:2;
char c:1;
int a;
};
#pragma pack()
struct M {
int m;
short l;
short k;
short x;
short n:2;
char a:2;
char c:2;
};
struct N {
int m:2;
short l;
short k;
short x;
short n:2;
char a:2;
char c:2;
};
int main()
{
printf("sizeof struct P = %d\n",sizeof(struct P));
printf("sizeof struct Q = %d\n",sizeof(struct Q));
printf("sizeof struct R = %d\n",sizeof(struct R));
printf("sizeof struct M = %d\n",sizeof(struct M));
printf("sizeof struct N = %d\n",sizeof(struct N));
return 0;
}
I am getting the sizeof(struct P) and sizeof(struct Q) as 8 bytes. This means that, character and integers will be considered separately and char will not be placed in integer space even if integer is of bit field type and free space is available. Again entire structure is aligned to the boundary of sizeof(int) and hence total size would be 4+1+3 padding bytes in case of P. If I use #pragma pack(1), I get 9 bytes and integers are now not naturally aligned and also entire structure is packed an not aligned to the boundary of integer type.
Considering the same concept, I was expecting sizeof(struct N) to be [4 byte for int, + 2 byte short + 2 byte short + 2 byte short + 2 byte for short + 1 byte for two char type combined + 3 for alignment = 16 bytes.
But sizeof(struct N) is 12bytes and not 16 bytes. Why size of M and N are not same?