yezi said:
then, which means if the memory is continuous, the memory should like
the following :
[snipped by yezi and reincluded by me]
struct example {
int foo;
int bar:5;
int baz;
} qux;
No. sizeof(int) * CHAR_BIT for qux.foo
Followed by an unspecifed amount of padding bits, followed by
3 bits for anystuff which is not belong to the structure;
No, not necessary 3 bit, but another unspecifed amount of padding bits,
which will result in correct alignment for the next struct member.
No, sizeof(int) * CHAR_BIT here too.
Is that understanding right?
No.
CHAR_BIT is at least 8, and 8 is the most common value in todays
implementations, but other values do exist. There are systems with
9 bit characters, and 36 bit integers for example.
sizeof(int) must be at least 2 on implementations where CHAR_BIT is 8,
but more common today are 4, and 8 is not unheard of.
An implementation is allowed to insert padding (unused memory space)
between members in a struct, so that all members will be properly
aligned. The amount of padding is implementation specific, and may
vary between platform, between compilers, between compiler versions,
and possibly depending on compiler settings. In practice it can be
a good idea to put the larger sized members first in a struct, and
to have same sized members adjacent to each other, to minimize the
amount of padding.
/Niklas Norrthon