关于几道sizeof题的疑问??

younggunz 2006-05-30 08:41:25
1.struct test
{
char a:2;
short b:2;
char c;
};
sizeof(test) == 6??为何是6??我觉得应该是2啊,如同
struct test{
unsigned short a:4;
unsigned short b:5;
unsigned short c:9;
unsigned short d:5;
};
sizeof(test)=4一样


2.struct a
{
unsigned aa;
unsigned bb;
unsigned long cc;

};
sizeof(a)=12,为何是12???我觉得应该是8啊
...全文
101 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
无知者无谓 2006-05-30
  • 打赏
  • 举报
回复
虽然你结帖了,不对的我还得说,
1.struct test
{
char a:2;
short b:2;
char c;
};

对于这个不同的编译器有不同的做法,不能像xpdavis(咕嘟) 一句话就完事的。
下面的代码:
struct test
{
char a:2;
short b:2;
char c;
};

int main ()
{
struct test *t = (struct test*)malloc (sizeof(struct test));
printf ("structure size is %d\n", sizeof (struct test));
printf ("0x%08X\t0x%08X \n", (unsigned)t, (unsigned)(&(t->c)));
}
再gcc编译的输出是:
structure size is 2
0x0804A008 0x0804A009

并没有“不同类型的位域不能合并”的现象
younggunz 2006-05-30
  • 打赏
  • 举报
回复
谢谢楼上的 ,汗啊 ,我一直就以为unsigned=unsigned short啊
结帖 ,送分~~~
铖邑 2006-05-30
  • 打赏
  • 举报
回复
1.不同类型的位域不能合并,所以是6,每个成员占用2个字节

2.unsigned=unsigned int占4个字节,所以是12
freshman1995 2006-05-30
  • 打赏
  • 举报
回复
凑一下热闹,不同的顺序有不同的结果。
struct test1
{
char a:2;
short b:2;
char c;
};

struct test2
{
char a:2;
char c;
short b:2;
};
他们的结果是不同的,sizeof(test1)=6,sizeof(test2)=4
原因就是后者a先与c对齐,然后合并与b对齐。

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧