Greko2009
Greko2009

Reputation: 563

Displaying the address of a string

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?

Upvotes: 38

Views: 68818

Answers (4)

user1203803
user1203803

Reputation:

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;

Upvotes: 68

Michel Keijzers
Michel Keijzers

Reputation: 15357

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.

Upvotes: 14

Rich Walter
Rich Walter

Reputation: 9

This also works:

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

Upvotes: 0

triclosan
triclosan

Reputation: 5714

or so:

std::cout << "Pointer address = " << &hello[0] << std::endl;

Upvotes: 4

Related Questions