关于C#不安全代码的指针问题
QFord 2009-01-19 09:44:53 //译者认为原书是对的,所以拿到这里和大家探讨一下。谢谢大家的关注!
//下面的代码是根据原书编写的
//如果我的想法是错误的,欢迎大家指正。
//"Address of myInt",应该是Address of ptrToMyInt即ptrToMyInt指针的地址(原作者错误,第4版电子版中仍未更正)
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
namespace ProgrammerTest
{
class Program
{
static void Main(string[] args)
{
unsafe {
int myInt;
//定义一个证书指针并将myInt的地址分配给它。
int* ptrToMyInt = &myInt;
//使用指针间接寻址为myInt赋值
*ptrToMyInt = 123;
//输出一些状态
Console.WriteLine("Value of myInt {0}",myInt );
Console.WriteLine("Address of myInt:{0:X}", (int)&ptrToMyInt);//注意这行,我认为应该是Address of ptrToMyInt!!!
/*原书代码到此为止,下面的代码是我新加的,用来验证自己的想法*/
Console.WriteLine("Value of ptrtoMyInt:{0:X}",(int)ptrToMyInt);
Console.WriteLine("Address of myInt:{0:X}",(int) &myInt);
//上面的两行代码,前一行输出ptrToMyInt指针的值,也就是myInt变量的地址;后一行输出myInt变量地址的值;两个值是一致的。
Console.ReadKey();
}
}
}
}