69,382
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
//using namespace std;
struct foo
{
//short s; //c1 00000002,s 00000000,c2 00000003,i 00000004
char c1;
//short s; //c1 00000000,s 00000002,c2 00000004,i 00000008
char c2;
//short s; //c1 00000000,s 00000002,c2 00000001,i 00000004
int i;
short s; //c1 00000000,s 00000008,c2 00000001,i 00000004
};
/*
这个程序运行在VC6.0下:
对于第1、3、4这三种情况来讲,我的理解是以4字节为单位对齐,
这样的结果都好理解,
可是第2种情况,实在不明白,各位帮解说下,
还有就是内存以多少字节为单位对齐,是CPU的事情,还是编译器的事情?
好像VC里面工程设置里面C/C++选项里面有个struct member alignment
但是我改变设置,输出也不改变。
*/
int main()
{
struct foo a;
printf("c1 %p, s %p, c2 %p, i %p\n",
(unsigned int)(void*)&a.c1 - (unsigned int)(void*)&a,
(unsigned int)(void*)&a.s - (unsigned int)(void*)&a,
(unsigned int)(void*)&a.c2 - (unsigned int)(void*)&a,
(unsigned int)(void*)&a.i - (unsigned int)(void*)&a);
printf("%d\n",sizeof(a));
return 0;
}
struct foo
{
char c1;
short s; //c1 00000000,s 00000002,c2 00000004,i 00000008
char c2;
int i;
};