Search code examples
pointersformattingc++-clistring-formattingmessagebox

How to show a pointer address with a messagebox in VS 2008 C++


I have been trying to show the pointer address in a messagebox and need your experience. Here is the code that kind-of works:

int MyVar;
int *PMyVar;
MyVar = 5;
PMyVar = &MyVar;
MessageBox::Show("value of MyVar: \n " + Convert::ToString(&PMyVar), "Pointer value");

The running program shows:

value of MyVar:
True

I am trying to show the address of the pointer, such as 0xfc00 (just a guess) instead of True. How do I show the hexadecimal address of a pointer with MessageBox?

Thanks for your help!


Solution

  • The type of &PMyVar is int**, Convert::ToString() does not have overloads that accepts pointer types. You'll have to cast it to a supported type. Pointer values can be 4 or 8 bytes so the best choice is UInt64:

      String^ str = String::Format("{0:X8}", (UInt64)&PMyVar);
      MessageBox:Show(str);
    

    Using String::Format() like this is called composite formatting, the "X" format provides formatting to hexadecimal. Do favor using the debugger instead of writing this kind of code.