大家好我对c ++中的字符指针有疑问.每当我们在c ++ char*p ="你好吗?"中创建一个字符指针时,p 应该包含内存位置的地址,其中包含"你好吗"的值.
但是我对一个samle代码和输出感到困惑.为什么要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;
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
how are you
0xbfac1eb0
h
Run Code Online (Sandbox Code Playgroud)
如果你想打印地址,那么你要转换char*
为void*
,as
const char *str = "how are you\n";
cout << (void*) str << endl;
Run Code Online (Sandbox Code Playgroud)
中投的由于缺少,cout
认为str
作为const char*
(这实际上是)等cout
认为你打算打印的空值终止字符串字符!
想一想:如果你想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);
Run Code Online (Sandbox Code Playgroud)
在没有强制转换的情况下,会调用第一个重载,但是当你强制转换时void*
,会调用第二个重载!