-4

Here in this code

#include<stdio.h>
void main()
{
    struct bits{
        unsigned a:5;
        unsigned b:5;
        char c;
        int d;
    } bit1;

    printf("%d",sizeof(bit1));
}

the output is 5
please explain how did 5 come

3
  • search hundred of duplicate about this on SO.
    – Stargateur
    Dec 17, 2017 at 16:07
  • What did you expect?
    – klutt
    Dec 17, 2017 at 16:08
  • I want to know how 5 comes that i expect Dec 17, 2017 at 16:09

1 Answer 1

1

Seems you are using Turbo C(windows). In TurboC compiler by default integer is short integer which is of 2 bytes(16 bits).

Next come to sizeof, you are trying to print sizeof structure, which is nothing sum of sizeof all data member.

The first member of struct bits is unsigned a : 5, when compiler will see first see unsigned it allocates 2 bytes or 16 bits for this, out of 16 bits you are using only 5 bits i.e still you can store 11 bits.

The next member is unsigned b:5 this will be served in same previous memory, so still size is 2 bytes. till now memory allocation will be looks like

----------------------------------------------------------------------
|   p |   p |   p | p | p | p | b | b | b | b | b | a | a | a | a | a |
----------------------------------------------------------------------
0x115 0x114 0x113..         ........                               0x100
MSB                                                                LSB 
a means for a 5 bits
b means for b 5 bits
p means padding or wastage.

if you analyse above figure, first 5 bits for a, next 5 bits for b, now how many pending out of 16 bits ? 6 bits right ? can you store a char(8 bit) in remaining 6 bits, answer is No. So remaining 6 bits will be holes in structure(I shown is p which is padding)

So next for char c it will again allocate separate 1 bytes, so till now 2+1 = 3 bytes.

Next member of structure is d which is again integer, so for this 2 bytes will be allocated. So total 2+1+ 2 = 5 bytes will be allocated for whole structure.

I hope you got it.

1
  • 1
    c is stored in a separate object not because the eight bits it needs do not fit in the bits remaining in the bytes allocated for a and b but because it is a regular object, not a bit-field, so it is stored separately regardless. This is per 6.2.6.1 of C 2011, but note 2 (paragraph 3) of clause 3.14 tell us explicitly: “A bit-field and an adjacent non-bit-field member are in separate memory locations.” Dec 17, 2017 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.