36

I have this code:

char* hello = "Hello World";
std::cout << "Pointer value = " << hello << std::endl;
std::cout << "Pointer address = " << &hello << std::endl;

And here is the result:

Pointer value = Hello World
Pointer address = 0012FF74

When I debug to my program using OllyDbg, I see that the value of 0x0012FF74 is e.g. 0x00412374.

Is there any way I can print the actual address that hello points to?

Greko2009
  • 443
  • 1
  • 5
  • 11

4 Answers4

63

If you use &hello it prints the address of the pointer, not the address of the string. Cast the pointer to a void* to use the correct overload of operator<<.

std::cout << "String address = " << static_cast<void*>(hello) << std::endl;
marceloow
  • 117
  • 9
13

I don't have a compiler but probably the following works:

std::cout << "Pointer address = " << (void*) hello << std::endl;

Reason: using only hello would treat is as a string (char array), by casting it to a void pointer it will be shown as hex address.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
4

or so:

std::cout << "Pointer address = " << &hello[0] << std::endl;
triclosan
  • 5,578
  • 6
  • 26
  • 50
0

This also works:

std::cout << "Pointer address = " << (int *)hello << std::endl;