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
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
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 byte
s will be allocated. So total 2+1+ 2 = 5 bytes
will be allocated for whole structure.
I hope you got it.