问题描述
这:
const char * terry =hello;
cout<< terry;
打印 hello
,而不是内存地址'h'
。为什么会发生这种情况?
原因是 std :: cout
会将 char *
作为指向C风格字符串(的第一个字符)的指针,并将其打印。如果您想改用地址,则只需将其转换为不是的指针,例如:
cout<< (void *)terry;
(或使用 const void *
如果你在这个特殊情况下,更多的是纯粹主义者而不是实用主义者,你也可以使用C ++ static_cast
:
cout<< static_cast< const void *> (terry);
虽然在这种情况下没有必要,但是转换为 void *
将工作正常。以下示例代码显示了操作中的所有这些选项:
#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 *> (毛圈) '\\\
';
return 0;
}
输出(地址在您的环境中可能不同):
hello
$请注意,当使用
0x8048870
0x8048870
0x8048870
static_cast
时,你应该确保你不要试图丢弃constness与static_cast< void *>
(这是const_cast
用于)。这是较新的C ++类型转换所做的检查之一,而旧样式的转换没有这个限制。This:
const char * terry = "hello"; cout<<terry;
prints
hello
instead of the memory address of the'h'
. Why is this happening?解决方案The reason for that is that
std::cout
will treat achar *
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;
(or use the
const void *
cast if you're worried about casting away constness, something that's not an issue in this particular case).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);
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 << '\n'; std::cout << (void *) terry << '\n'; std::cout << (const void *) terry << '\n'; std::cout << static_cast<const void *> (terry) << '\n'; return 0; }
outputting (the address may be different in your environment):
hello 0x8048870 0x8048870 0x8048870
Note that, when using the
static_cast
, you should ensure you don't try to cast away the constness withstatic_cast <void *>
(that's whatconst_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 *参数打印字符串,而不是指针值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!