如何在C#中显示指针地址?
自从我用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";
使用Console.WriteLine(*cp);
给我指针地址的当前值…如果我想显示实际地址怎么办?
Console.WriteLine(new IntPtr(cp));
请记住,使用托管代码,垃圾收集器可以随意移动您。 如果您的地址很重要,请确保将对象固定 。
将指针转换为字节类型。
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);
char c = 'c'; unsafe { Console.WriteLine("0x{0:x}", (ulong)&c); Console.WriteLine($"0x{(ulong)&c:x}"); }
这将显示类似… 0x123abc(两次)