简体   繁体   English

如何用位域计算结构的大小?

[英]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?我将 output 设为 24。它如何等同于它?

As your implementation accepts long int y: 33;由于您的实现接受long int y: 33; a long int hase more than 32 bits on your system, so I shall assume 64.一个 long int 在你的系统上有超过 32 位,所以我假设是 64。

If plain int are also 64 bits, the result of 24 is normal.如果plain int也是64位,24的结果是正常的。

If they are only 32 bits, you have encountered padding and alignment .如果它们只有 32 位,则您遇到了填充alignment For performance reasons, 64 bits types on 64 bits systems are aligned on a 64 bits boundary.出于性能原因,64 位系统上的 64 位类型在 64 位边界上对齐。 So you have:所以你有了:

  • 4 bytes for the first int第一个 int 4 个字节
  • 4 padding bytes to have a 8 bytes boundary 4 个填充字节以具有 8 个字节的边界
  • 8 bytes for the container of the bit field位域的容器 8 个字节
  • 4 bytes for the second int第二个 int 为 4 个字节
  • 4 padding bytes to allow proper alignment of arrays 4 个填充字节以允许 arrays 的正确 alignment

Total: 24 bytes总计:24 字节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM