2
下面是示例程序及其輸出。堆棧內存分配和對齊問題
typedef struct{
char name[30];
int empno;
int sal;
}empd, * empdPtr;
int main(){
int x = 1;
char y = 2;
int z = 3;
empd e;
empdPtr ep = &e;
printf("sizeof ep = %d e = %d \n",sizeof(ep),sizeof(e));
printf("Address of e = %u, ep = %u x = %u y = %u z = %u\n",&e,&ep,&x,&y,&z);
printf("Address of e.name = %u e.empno = %u e.sal = %u \n",&e.name,&e.empno,&e.sal);
return 0;
}
$ ./a.exe
sizeof ep = 4 e = 40
Address of e = 2289536, ep = 2289532 x = 2289596 y = 2289595 z = 2289588
Address of e.name = 2289536 e.empno = 2289568 e.sal = 2289572
這裏&電子商務地址和& Z之間的差爲52但的sizeof(e)是40.爲什麼編譯器中加入12多個字節,即使40個字節就足夠了?
編譯器也可以將填充添加到結構中。 – 2010-12-17 12:08:48
@Francisco事實上,這個編譯器已經這樣做了,因爲empd結構,如果打包,會消耗38個字節 – 2010-12-17 12:18:39
你能否給出一些相同的細節? – Thangaraj 2010-12-17 12:27:57