Bit-fields at two separate locations in a Structure in C -
in structure have contiguous bit-fields; is, 1 after other , adjacent each other — example:
struct demo { char a; char b:1; char c:2; char d:2; int e; } demo1;
the size of demo1
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 use sizeof(demo1)
, gives me 8 bytes — want know how these bit-fields presented in memory.
if calculated above structure size should be:
- size =
a
(1 byte) +b
(4 bytes) +c
(1 byte) +d
(1 byte) +e
(4 bytes)
during programming don't bother thing how size calculated using sizeof
, don't use bit-fields @ 2 different locations, type of question asked interviewers.
consecutive (non-zero width) bit-fields can merged single memory location, while bit-field followed non-bit-field distinct memory locations.
struct demo { char a; int b:1; char c; char d; int e:2; } demo1;
so in struct
, there 1 non bit-field , 1 bit-field , 2 non bit-fields , bit-field.
having non-bit-field (or zero-length bit-field) right after bit-field member, follows next different/independent memory location/object.
and also:
a compiler not reorder elements of struct
, because violate c standard. section 6.7.2.1 of c99 standard states:
within structure object, non-bit-field members , units in bit-fields reside have addresses increase in order in declared.
Comments
Post a Comment