C++ 显示字符串的地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9377407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:45:51  来源:igfitidea点击:

Displaying the address of a string

c++pointers

提问by Greko2009

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.

当我使用 OllyDbg 调试我的程序时,我看到 0x0012FF74 的值是例如 0x00412374。

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

有什么办法可以打印hello指向的实际地址吗?

回答by

If you use &helloit 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<<.

如果你使用&hello它打印指针的地址,而不是字符串的地址。将指针强制转换为 avoid*以使用 的正确重载operator<<

std::cout << "String address = " << static_cast<void*>(hello) << std::endl;

回答by Michel Keijzers

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.

原因:仅使用 hello 会将 is 视为字符串(字符数组),通过将其转换为 void 指针,它将显示为十六进制地址。

回答by triclosan

or so:

或者:

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

回答by Rich Walter

This also works:

这也有效:

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