关于 C 语言数据对齐的试验
下面的小程序是关于数据对齐的一个试验,在我的 2.4 内核的 Linux 上运行结果如下:
size of Foo1: 16
size of Foo2: 12
size of Foo3: 12
size of Foo4: 10
#include <stdio.h>
struct Foo1
{
char a;
int b;
char c;
int d;
};
#pragma pack (2)
struct Foo2
{
char a;
int b;
char c;
int d;
};
#pragma pack ()
struct Foo3
{
char a;
char c;
int b;
int d;
};

struct Foo4
{
char a;
int b;
char c;
int d;
} __attribute__ ((__packed__));

int main(int argc, char **argv)
{
printf("size of Foo1: %d ", sizeof(struct Foo1));
printf("size of Foo2: %d ", sizeof(struct Foo2));
printf("size of Foo3: %d ", sizeof(struct Foo3));
printf("size of Foo4: %d ", sizeof(struct Foo4));

return 0;
}
~
1、 Foo1 未经过任何处理的,由于整型需要按 4 字节对齐,因此实际存储结果如下,占用 16 个字节空间
2、Foo2 通过 #pragma pack (2) ,将对齐方式改为 2 字节对齐,实际存储结果如下,占用 12 字节空间
3、 Foo3, 通过 #pragma pack (),又恢复到默认的 4 字节对齐方式,但是由于调整了变量的顺序,实际存储结果如下,占用 12 字节空间
4、Foo4, 通过 GCC 的 __packed__ 的扩展属性,禁止对齐,得到如下结果,占用空间 10 字节

956

被折叠的 条评论
为什么被折叠?



