Questions about C bitfields

独自空忆成欢 提交于 2019-11-27 15:38:40

Because a and c are not contiguous, they each reserve a full int's worth of memory space. If you move a and c together, the size of the struct becomes 8 bytes.

Moreover, you are telling the compiler that you want a to occupy only 1 bit, not 1 byte. So even though a and c next to each other should occupy only 3 bits total (still under a single byte), the combination of a and c still become word-aligned in memory on your 32-bit machine, hence occupying a full 4 bytes in addition to the int b.

Similarly, you would find that

struct s{
unsigned int b;
short s1;
short s2;
};

occupies 8 bytes, while

struct s{
short s1;
unsigned int b;
short s2;
};

occupies 12 bytes because in the latter case, the two shorts each sit in their own 32-bit alignment.

1) They originated in C, but are part of C++ too, unfortunately.

2) Yes, or within a class in C++.

3) As well as saving memory, they can be used for some forms of bit twiddling. However, both memory saving and twiddling are inherently implementation dependent - if you want to write portable software, avoid bit fields.

Its C.

Your comiler has rounded the memory allocation to 12 bytes for alignment purposes. Most computer memory syubsystems can't handle byte addressing.

Your program is working exactly as I'd expect. The compiler allocates adjacent bitfields into the same memory word, but yours are separated by a non-bitfield.

Move the bitfields next to each other and you'll probably get 8, which is the size of two ints on your machine. The bitfields would be packed into one int. This is compiler specific, however.

Bitfields are useful for saving space, but not much else.

Bitfields are widely used in firmware to map different fields in registers. This save a lot of manual bitwise operations which would have been necessary to read / write fields without it. One disadvantage is you can't take address of bitfields.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!