引:
struct s {char c;int i;}; 在sizeof(char)=1 sizeof(int)=4的情况下sizeof(struct s)
为什么经常是8不是5?
这个就是对齐(alignment)的缘故。
那么什么是对齐?现代计算机中内存空间都是按照byte划分的,从理论上讲似乎对任何类型的
变量的访问可以从任何地址开始,但实际情况是在访问特定变量的时候经常在特定的内存地址
访问,这就是对齐。为什么呢?msdn for vc6中有这么一段:
This principle is especially important when you write code for porting to multiple
processors. A misaligned 4-byte data member, which is on an address that is not a
multiple of four, causes a performance penalty with an 80386 processor and a
hardware exception with a MIPS® RISC processor. In the latter case, although
the system handles the exception, the performance penalty is significantly greater.
在c99标准中对对齐提及的不多,如何对齐的策略基本依赖于实现(implement),就是编译器,
而编译器是和硬件平台密切相关,所以间接的也和硬件平台相关。
在看c99手册时要注意一个问题:就是指针(pointer)对齐和指针类型(pointer type)对齐。打
个比方:
short *pc;所谓指针类型对齐的意思就是&pc%(short *这种指针类型的alignment-requirement)
= 0。
而指针对齐是说pc%(short类型的alignment-requirement) = 0。
pc=2002代表指针对齐了,而&pc=2002代表指针类型不对齐(当然前提是short *的
alignment-requirement = 4)。
c99中6.3.2.3 Pointers第5条和第7条说的是指针对齐,这两条说的是整数和指针转化的问题,
转化过程中有可能出现不对齐事件,比如short *pi = 2001,这种行为就是undefined,因为一
旦使用*pi,就发生不对齐的事件。在这两条中英文出现的是pointer aligned,按我的理解指的
是指针对齐。
c99中6.2.5 Types第27条说的是指针类型对齐,任何void*和char* have the same alignment
requirements,任何struct* have the same alignment requirements,任何union* have the
same alignment requirements。在这条中英文出现的是pointer have the same alignment
requirements,按我的理解是指针类型对齐。
我感觉自己似乎没大说明白,并且对6.2.5 Types第27条和6.3.2.3 Pointers第5条和第7条这种
区别也不一定理解对,不过也许对您理解上有帮助。