开发者

sizeof(Structure) Confusion

开发者 https://www.devze.com 2023-01-04 12:14 出处:网络
In the following piece of code, #include<stdio.h> typedef struct { int bit1:1; int bit3:4; int bit4:4;

In the following piece of code,

#include<stdio.h>
typedef struct {
    int bit1:1;
    int bit3:4;
    int bit4:4;
} node;

int main(){
    node n,n1,n2,ff[10];

    printf("%d\n",sizeof(node));
    return 0;
}

How do I predict the size of the开发者_JAVA技巧 structure?


You cannot predict it without knowing the compiler and the target platform it compiles to.


It depends on the platform and the compiler settings (packing, alignment, 32/64 machine)

According to comp.lang.c FAQ list

"Bit-fields are thought to be nonportable, although they are no less portable than other parts of the language."


Unpredictable in general, but practically speaking it'll come out sizeof(int) more often than not. Which itself is very often 4; less commonly 2 and surely 8 at times.

Most of the time the bit fields will be packed and most of the time the int type will have 9 or more bits of storage.


You will find that the size of your structure changes based on compiler optimization settings. I'd predict anywhere between 2 and 12 bytes for this structure.

Even when using bit-fields like you do, you can't always predict what the size of a struct is going to be. The compiler may have every bit-field take up the full space of an int, or possibly just the 1 or 4 bits that you specify. Using bit-fields, while it is great on memory storage space, is often bad for running time and executable size.


Usually every compiler decides how to pack the union so you can't make many assumptions on the final size. They can decide a different layout according to its parameters.


Add the bit-field sizes, divide by 8*sizeof(int), and take the ceiling of that value. In your example, it'll be 4.

0

精彩评论

暂无评论...
验证码 换一张
取 消