考慮以下代碼:
-
C# code
-
unsafe { byte b = 3; double d = 10.0; int i = 5; byte* pb = &b; double* pd = &d; int* pi = &i; Console.WriteLine("Address of b is 0x{0:X},size is {1},value is {2}", (uint)pb, sizeof(byte), b); Console.WriteLine("Address of d is 0x{0:X},size is {1},value is {2}", (uint)pd, sizeof(double), d); Console.WriteLine("Address of i is 0x{0:X},size is {1},value is {2}", (uint)pi, sizeof(int), i); Console.WriteLine("Address of pb is 0x{0:X},size is {1},value is 0x{2:X}", (uint)&pb, sizeof(byte*), (uint)pb); Console.WriteLine("Address of pd is 0x{0:X},size is {1},value is 0x{2:X}", (uint)&pd, sizeof(double*), (uint)pd); Console.WriteLine("Address of pi is 0x{0:X},size is {1},value is 0x{2:X}", (uint)&pi, sizeof(int*), (uint)pi); }
在我機子上顯示的輸出結果是
Address of b is 0x12F46C,size is 1,value is 3
Address of d is 0x12F464,size is 8,value is 10
Address of i is 0x12F460,size is 4,value is 5
Address of pb is 0x12F45C,size is 4,value is 0x12F46C
Address of pd is 0x12F458,size is 4,value is 0x12F464
Address of pi is 0x12F454,size is 4,value is 0x12F460
現在我的問題是:看代碼,堆棧應該是從高地址向低地址向下填充,byte只佔1個位元組,而32位處理器系統堆棧的記憶體塊總是按照4位元組的倍數進行分配的。b的地址是0x12F46C,那麼b這個值應該儲存在0x12F468~0x12F46B中,佔4個位元組,然後為d分配記憶體,double類型佔8個個位元組,其地址應該是0x12F468,d應該儲存在0x12F460~0x12F467中,但為什麼輸出結果b佔了8個位元組的記憶體而d卻只佔了4個位元組的記憶體呢。
另外如果把代碼的最後三行去掉,即變成
-
C# code
-
unsafe { byte b = 3; double d = 10.0; int i = 5; byte* pb = &b; double* pd = &d; int* pi = &i; Console.WriteLine("Address of b is 0x{0:X},size is {1},value is {2}", (uint)pb, sizeof(byte), b); Console.WriteLine("Address of d is 0x{0:X},size is {1},value is {2}", (uint)pd, sizeof(double), d); Console.WriteLine("Address of i is 0x{0:X},size is {1},value is {2}", (uint)pi, sizeof(int), i);}
輸出結果為
Address of b is 0x12F45C,size is 1,value is 3
Address of d is 0x12F460,size is 8,value is 10
Address of i is 0x12F468,size is 4,value is 5
記憶體配置變成了從低地址到高地址向上填充,但此時b佔了4個位元組,d佔了8個位元組,何解?