考虑以下代码:
C# code
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
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); }
在我机子上显示的输出结果是
Addressofbis0x12F46C,sizeis1,valueis3
Addressofdis0x12F464,sizeis8,valueis10
Addressofiis0x12F460,sizeis4,valueis5
Addressofpbis0x12F45C,sizeis4,valueis0x12F46C
Addressofpdis0x12F458,sizeis4,valueis0x12F464
Addressofpiis0x12F454,sizeis4,valueis0x12F460
现在我的问题是:看代码,堆栈应该是从高地址向低地址向下填充,byte只占1个字节,而32位处理器系统堆栈的内存块总是按照4字节的倍数进行分配的。b的地址是0x12F46C,那么b这个值应该存储在0x12F468~0x12F46B中,占4个字节,然后为d分配内存,double类型占8个个字节,其地址应该是0x12F468,d应该存储在0x12F460~0x12F467中,但为什么输出结果b占了8个字节的内存而d却只占了4个字节的内存呢。
另外如果把代码的最后三行去掉,即变成
C# code
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
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); }
输出结果为
Addressofbis0x12F45C,sizeis1,valueis3
Addressofdis0x12F460,sizeis8,valueis10
Addressofiis0x12F468,sizeis4,valueis5
内存分配变成了从低地址到高地址向上填充,但此时b占了4个字节,d占了8个字节,何解?