19

I've not done any pointers since I've been programming in C# - and my C++ days were long ago. I thought I should refresh my knowledge and was just playing around with them because of another question on here. I understand them all okay, but I can't figure out how to write the pointer's address to the console...

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";

Using Console.WriteLine(*cp); gives me the current value at the pointer address... what if I want to display the actual address?

BenAlabaster
  • 37,733
  • 21
  • 106
  • 149
  • Not tried it but what does Console.WriteLine(cp); give you? – Lazarus Jan 13 '10 at 14:55
  • @Lazarus - You don't think that was the first thing I tried? LOL. Give me some credit, I'd already tried everything obvious before I came asking questions on here ;) – BenAlabaster Jan 13 '10 at 15:00

5 Answers5

25
Console.WriteLine(new IntPtr(cp));
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
4

Remember that with managed code the garbage collector is free to move things around on you. Make sure to pin your object down if your in a situation where the address matters.

Joel Coehoorn
  • 380,066
  • 110
  • 546
  • 781
  • Thanks Joel, I hadn't considered that yet. Like I said, I was just playing, I haven't had any real requirement to use pointers in my C# projects. – BenAlabaster Jan 13 '10 at 14:58
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);
bwest
  • 8,643
  • 3
  • 24
  • 54
Alan
  • 11
  • 1
  • woops, meant vhar not float in console write message. – Alan Aug 22 '15 at 12:28
  • string strcptr = Convert.ToString((long)cptr, 16); Console.WriteLine("Ox{0} is the char ptr hex address", strcptr); – Alan Aug 22 '15 at 13:37
0

Convert your pointer to byte type.

Yevhen
  • 1,839
  • 2
  • 14
  • 25
0
char c = 'c';

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

This will display something like ... 0x123abc (twice)

MarcioAB
  • 551
  • 1
  • 4
  • 11