Mr. Noob
Mr. Noob

Reputation: 47

How to calculate size of structure with bit field?

#include <stdio.h> 
struct test { 
unsigned int x; 
long int y : 33; 
unsigned int z; 
};  
int main() 
{ 
struct test t; 
printf("%d", sizeof(t)); 
return 0; 

}

I am getting the output as 24. How does it equate to that?

Upvotes: 2

Views: 62

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149175

As your implementation accepts long int y : 33; a long int hase more than 32 bits on your system, so I shall assume 64.

If plain int are also 64 bits, the result of 24 is normal.

If they are only 32 bits, you have encountered padding and alignment. For performance reasons, 64 bits types on 64 bits systems are aligned on a 64 bits boundary. So you have:

  • 4 bytes for the first int
  • 4 padding bytes to have a 8 bytes boundary
  • 8 bytes for the container of the bit field
  • 4 bytes for the second int
  • 4 padding bytes to allow proper alignment of arrays

Total: 24 bytes

Upvotes: 3

Related Questions