-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

klutt
  • 30,332
  • 17
  • 55
  • 95
Pritul Dave
  • 189
  • 1
  • 11

1 Answers1

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.

paul
  • 27
  • 10
Achal
  • 11,821
  • 2
  • 15
  • 37
  • 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.” – Eric Postpischil Dec 17 '17 at 16:45