Reputation: 22813
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 structure?
Upvotes: 0
Views: 327
Reputation: 1
Add the bit-field sizes, divide by 8*sizeof(int), and take the ceiling of that value. In your example, it'll be 4.
Upvotes: 0
Reputation: 4654
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.
Upvotes: 3
Reputation: 674
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.
Upvotes: 1
Reputation: 68942
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."
Upvotes: 3
Reputation: 133557
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.
Upvotes: 0
Reputation: 506837
You cannot predict it without knowing the compiler and the target platform it compiles to.
Upvotes: 9