我对 C++ 中的字符指针有疑问。每当我们在 C++ 中创建一个字符指针时:char *p="How are you doing"
, p 应该包含存储值“你好吗”的内存地址。
但是,我对示例代码和输出感到困惑。为什么 cout<<p
返回整个字符串?它应该给出内存地址的值。其次,为什么 cout<<*p
只给出字符串的第一个字符?
代码:
#include <iostream>
using namespace std;
int main () {
const char *str = "how are you\n";
int i[]={1,2,3};
cout << str << endl; // << is defined on char *.
cout << i << endl;
cout << *str << endl;
}
输出:
how are you
0xbfac1eb0
h
最佳答案
如果你想打印地址,那么你必须转换char*
至 void*
, 作为
const char *str = "how are you\n";
cout << (void*) str << endl;
在 Actor 缺席的情况下,cout
看到 str
作为const char*
(实际上是)等等cout
认为您打算打印以 null 结尾的 char 字符串!
想想:如果你想要coud << str
要打印地址,您将如何打印字符串本身?
--
无论如何,这里有更详细的解释:
operator<<
为 char*
重载以及void*
:
//first overload : free standing function
basic_ostream<char, _Traits>& operator<<(basic_ostream<char, _Traits>& _Ostr, const char *_Val);
//second overload : a member of basic_ostream<>
_Myt& operator<<(const void *_Val);
在没有强制转换的情况下,会调用第一个重载,但是当您强制转换为 void*
时,第二个重载被调用!
关于c++ - C++中的字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5270277/