与其他数据类型的指针相比,为什么指向char的指针行为不同

sam*_*rat 2 c++ pointers char

我对以下的陈述表示怀疑;

int intvalue = 3;
int *pointInt = &intvalue;

char* p = "string";
cout << pointInt << std::endl;  // this will give memory location of intvalue which is ok.
cout << p<< std::endl; // why this will give string value  rather than memory location of where string is stored?
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 5

因为有一个重载std::ostream& operator<<(std::ostream&, const char*),它假定它char*是以null结尾的字符串的第一个元素并打印出整个字符串.

您可以通过尝试流式传输有很多好玩的char*是不是一个null结尾的字符串的第一个元素:

#include <iostream>
int main()
{
  char c = 'x';
  std::cout << &c << std::endl;
}
Run Code Online (Sandbox Code Playgroud)