Hello People... I found this sample code online

int main(int argc, char* argv[])
{
        struct bitfield
        {
                signed int a:3;
                unsigned int b:13;
                unsigned int c:1;
        };
        struct bitfield bit1={2,14,1};
        printf("%d",sizeof(bit1));


        return 1;
}

I compiled this code on linux with gcc compiler and the output I got for this is 4. Can any one explain why this so ?

Because the compiler padded the structure elements up to whole bytes.

one byte for signed int a:3;
two bytes for unsigned int b:13;
and on byte for unsigned int c:1;

Try using the attribute packed like below and you'll get three bytes because again the compiler will pad the end of the structure up to wholes bytes..

#include <stdio.h>

int main(int argc, char* argv[])
{
        struct bitfield
        {
                signed int a:3;
                unsigned int b:13;
                unsigned int c:1;
        }__attribute__((packed));
        struct bitfield bit1={2,14,1};
       
	fprintf(stdout, "size of a->%lu\n", sizeof(bit1));

        return 1;
}

Edited 6 Years Ago by gerard4143: n/a

This question has already been answered. Start a new discussion instead.