C#指標未解決問題

來源:互聯網
上載者:User
考慮以下代碼:
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個位元組,何解? 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.