本文共 1044 字,大约阅读时间需要 3 分钟。
内存对齐的目的:
字,双字,和四字在自然边界上不需要在内存中对齐。(对字,双字,和四字来说,自然边界分别是偶数地址,可以被 4 整除的地址,和可以被 8 整除的地址。)无论如何,为了提高程序的性能,数据结构(尤其是栈)应该尽可能地在自然边界上对齐。原因在于,为了访问未对齐的内存,处理器需要作两次内存访问;然而,对齐的内存访问仅需要一次访问。一个字或双字操作数跨越了 4 字节边界,或者一个四字操作数跨越了 8 字节边界,被认为是未对齐的,从而需要两次总线周期来访问内存。一个字起始地址是奇数但却没有跨越字边界被认为是对齐的,能够在一个总线周期中被访问。
使用指令#pragma pack (n),编译器将按照 n 个字节对齐。 使用指令#pragma pack (),编译器将取消自定义字节对齐方式。3
#include <stdio.h> typedef struct TestStruct1 { char c1; short s; char c2; int i; }; int main(int argc, char * argv[]) { struct TestStruct1 a; printf("c1 %p,s %p,c2 %p,i %p\n", (unsigned int)&a.c1 - (unsigned int) &a, //(void *) means force transform to type of pointer . (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("size of short is %d\n",sizeof( short)); // 2 printf("size of TestStruct1 is %d\n",sizeof( TestStruct1 )); //12 return 0; } /*end of run!!!
c1 00000000,s 00000002,c2 00000004,i 00000008 size of short is 2 size of TestStruct1 is 12.
*/所以由此可得在内存中按4字节对齐
转载地址:http://jdtgf.baihongyu.com/