In a structure we normally have contiguous bit-fields; that is, one after the other and adjacent to each other — for example:
struct demo
{
char a;
char b:1;
char c:2;
char d:2;
int e;
} demo1;
The size of demo1
will be 8 bytes:
- size =
a
(1 byte) + bit-fields(1 byte) + gap(2 bytes) +e
(4 bytes))
Now consider following structure:
struct demo
{
char a;
int b:1;
char c;
char d;
int e:2;
} demo1;
When I use sizeof(demo1)
, it gives me 8 bytes — but I want to know how these bit-fields are presented in memory.
If calculated like above structure size should be:
- size =
a
(1 byte) +b
(4 bytes) +c
(1 byte) +d
(1 byte) +e
(4 bytes)
During programming we don't bother about this thing that how size will be calculated using sizeof
and we even don't use bit-fields at two different locations, but sometimes this type of question is asked by interviewers.