19

自从我用 C# 编程以来,我没有做过任何指示——而且我的 C++ 时代很久以前了。我想我应该更新我的知识,只是因为这里的另一个问题而和他们一起玩。我都理解它们,但我不知道如何将指针的地址写入控制台......

char c = 'c';
char d = 'd';
char e = 'e';

unsafe
{
    char* cp = &d;
    //How do I write the pointer address to the console?
    *cp = 'f';
    cp = &e;
    //How do I write the pointer address to the console?
    *cp = 'g';
    cp = &c;
    //How do I write the pointer address to the console?
    *cp = 'h';        
}
Console.WriteLine("c:{0}", c); //should display "c:h";
Console.WriteLine("d:{0}", d); //should display "d:f";
Console.WriteLine("e:{0}", e); //should display "e:g";

UsingConsole.WriteLine(*cp);给了我指针地址的当前值......如果我想显示实际地址怎么办?

4

5 回答 5

25
Console.WriteLine(new IntPtr(cp));
于 2010-01-13T14:55:30.577 回答
4

请记住,使用托管代码,垃圾收集器可以自由地在您身上移动东西。如果您在地址很重要的情况下,请确保将您的对象固定下来。

于 2010-01-13T14:57:52.037 回答
1
char* cptr;
char achr = 'a';
cptr = &achr;
string strcptr = Convert.ToString((long)cptr, 16);
Console.WriteLine("Ox{0} is the char ptr hex address", strcptr);
于 2015-08-22T12:27:09.893 回答
0

将指针转换为字节类型。

于 2010-01-13T14:55:01.950 回答
0
char c = 'c';

unsafe
{
  Console.WriteLine("0x{0:x}", (ulong)&c);
  Console.WriteLine($"0x{(ulong)&c:x}");
}

这将显示类似 ... 0x123abc (两次)

于 2017-06-26T13:54:43.023 回答