cout<<使用 char* 参数打印字符串,而不是指针值 [英] cout << with char* argument prints string, not pointer value
问题描述
这个:
const char * terry = "hello";
cout<<terry;
打印hello
而不是'h'
的内存地址.为什么会发生这种情况?
prints hello
instead of the memory address of the 'h'
. Why is this happening?
推荐答案
这样做的原因是 std::cout
会将 char *
视为指向(第一个字符)一个 C 风格的字符串并打印它.如果你想要地址,你可以把它转换成一个不是那样处理的指针,比如:
The reason for that is that std::cout
will treat a char *
as a pointer to (the first character of) a C-style string and print it as such. If you want the address instead, you can just cast it to a pointer that isn't treated that way, something like:
cout << (void *) terry;
(或使用 const void *
强制转换,如果您担心丢弃常量,在这种特殊情况下这不是问题).
(or use the const void *
cast if you're worried about casting away constness, something that's not an issue in this particular case).
如果您更喜欢纯粹主义者而不是实用主义者,您还可以使用 C++ static_cast
,如下所示:
If you're more of a purist than pragmatist, you can also use the C++ static_cast
, along the lines of:
cout << static_cast <const void *> (terry);
虽然在这种特殊情况下没有必要,但转换为 void *
会正常工作.以下示例代码显示了所有这些选项的作用:
though it's unnecessary in this particular case, the cast to a void *
will work fine. The following sample code shows all these options in action:
#include <iostream>
int main (void) {
const char *terry = "hello";
std::cout << terry << '
';
std::cout << (void *) terry << '
';
std::cout << (const void *) terry << '
';
std::cout << static_cast<const void *> (terry) << '
';
return 0;
}
输出(地址在你的环境中可能不同):
outputting (the address may be different in your environment):
hello
0x8048870
0x8048870
0x8048870
请注意,在使用 static_cast
时,您应该确保不要尝试使用 static_cast
抛弃常量性(这就是 const_cast
是为了).这是由较新的 C++ 强制转换完成的检查之一,旧式强制转换没有此限制.
Note that, when using the static_cast
, you should ensure you don't try to cast away the constness with static_cast <void *>
(that's what const_cast
is for). This is one of the checks done by the newer C++ casts and the old-style cast does not have this limitation.
这篇关于cout<<使用 char* 参数打印字符串,而不是指针值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!