带有位域的结构体的sizeof

C++: sizeof of struct with bit fields

本文关键字:结构体 sizeof 位域      更新时间:2023-10-16

为什么gcc返回13作为以下类的sizeof ?在我看来,我们应该得到e(4字节)+ d(4字节)+ 1字节(对于a和b) = 9字节。如果是对齐,那么大多数32位系统不是在8字节边界上对齐吗?

class A {
  unsigned char a:1;
  unsigned char b:4;
  unsigned int d;
  A* e;
} __attribute__((__packed__));

int main( int argc, char *argv[] )
{
  cout << sizeof(A) << endl;
}

./a.o ut13

您很可能在64位平台上运行,指针的大小不是4而是8个字节。在a *上设置sizeof,然后打印出来

具有位域的结构体的实际大小取决于实现,因此gcc决定的大小将是正确的