C语言结构体位域示例大小存疑:书中16位大小是否准确?
Hey there! Let me walk you through this bit-field struct example step by step since you're currently learning this part of C basics.
Breaking Down the Bit-Field Struct Size
First, let's start with the complete example code (I'll fill in the truncated part based on the description you gave):
#include <stdio.h> #include <stdbool.h> struct test { bool opaque : 1; // 1 bit for the boolean flag unsigned int fill_color : 3; // 3 bits for fill color options unsigned int border_color : 3; // 3 bits for border color unsigned int border_style : 3; // 3 bits for border style };
1. No-Padding Size Calculation
The book mentions the size is 10 bits without padding, which adds up perfectly when we tally each bit-field:
opaque(bool type): 1 bitfill_color(unsigned int type): 3 bitsborder_color(unsigned int type): 3 bitsborder_style(unsigned int type): 3 bits- Total without padding: 1 + 3 + 3 + 3 = 10 bits
2. Why the Actual Size is 16 Bits (2 Bytes)?
This boils down to C's struct alignment and bit-field storage rules:
- Compilers align structs to the size of the largest basic type used in the bit-fields (or a standard alignment boundary, depending on the system). In this case, the compiler is enforcing alignment to a 16-bit (2-byte) boundary.
- Even though we only use 10 bits of actual data, the compiler adds 6 bits of padding to make the struct's total size a multiple of 16 bits. This padding ensures the CPU can access the struct's data efficiently, as processors work best with memory addresses aligned to specific byte boundaries.
- A quick side note: Some compilers might allow grouping bit-fields of different types into the same storage unit, but alignment requirements almost always take priority to maintain performance.
If you want to confirm this behavior on your own system, you can run a simple test using the sizeof operator:
int main() { printf("Size of struct test: %zu bytes (%zu bits)\n", sizeof(struct test), sizeof(struct test) * 8); return 0; }
This will print the exact size of the struct in both bytes and bits for your specific compiler and environment.
内容的提问来源于stack exchange,提问作者AlexQualcosa
相关产品推荐
相关产品推荐

