闲来无事,尝试下面的代码 :
(64位OpenSuse机器)
#include <stdio.h>
struct Empty
{
};
struct EEmpty
{
struct Empty e;
struct Empty e1;
};
int main()
{
printf("size of Empty struct is : %d\n", sizeof(struct Empty));
printf("size of EEmpty struct is : %d\n", sizeof(struct EEmpty));
struct Empty w;
int a;
printf("Addr w : %p\n", &w);
printf("Addr a : %p\n", &a);
return 0;
}
首先使用GCC编译 :
xxx@WS-TAO0023:gcc c_test.c
xxx@WS-TAO0023:./a.out
输出:
size of Empty struct is : 0
size of EEmpty struct is : 0
Addr w : 0x7fffe51b9710
Addr a : 0x7fffe51b970c
然后使用G++编译 :
xxx@WS-TAO0023:g++ c_test.c
xxx@WS-TAO0023:./a.out
输出:
size of Empty struct is : 1
size of EEmpty struct is : 2
Addr w : 0x7fffa7513b1f
Addr a : 0x7fffa7513b18
可以看到为了保证每个变量(对象) 有唯一的内存地址 :
* C++编译器强制让空结构体大小为1 byte
* C编译器虽然保持空结构体大小为 0 , 但是仍然为它类型的变量分配了空间 .
考虑到内存对齐会导致上面的地址差距大于实际上空结构体占有的内存大小, 对代码进行修改:
//int a; 替换成下面一行
char a;
GCC下编译得到 :
size of Empty struct is : 0 byte
size of EEmpty struct is : 0 byte
Addr w : 0x7fff683b6150
Addr a : 0x7fff683b614f
G++下编译得到
size of Empty struct is : 1 byte
size of EEmpty struct is : 2 byte
Addr w : 0x7fff5ce39fef
Addr a : 0x7fff5ce39fee
可见对于空结构体, 大家都只给它最小的1 byte 的内存 .