C++: sizeof of struct with bit fields

眉间皱痕 提交于 2020-03-27 06:48:38

问题


Why is gcc giving returning 13 as the sizeof of the following class ? It seems to me that we should get e (4 bytes) + d (4 bytes) + 1 byte (for a and b) = 9 bytes. If it was alignment, aren't most 32 bit systems aligned on 8 byte boundaries ?

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.out 13


回答1:


You are very likely running on a 64 bit platform and the size of the pointer is not 4 but 8 bytes. Just do a sizeof on A * and print it out.




回答2:


The actual size of structs with bitfields is implementation dependent, so whatever size gcc decides it to be would be right.



来源:https://stackoverflow.com/questions/7437423/c-sizeof-of-struct-with-bit-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!