题
自从我在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(两次)
不隶属于 StackOverflow