c++ - C++中的字符指针

标签 c++ pointers

我对 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/

相关文章:

c - 函数什么时候必须通过引用接收参数才能改变参数的某些内容?

c - (arr + 2) 等同于 *(arr + 2) 。如何?

传递给类构造函数的 C++ 字符串 - 链接器错误

c++ - 如何在不使用 std::forward 的情况下调用成员变量的 move 构造函数?

c++ - 由于我无法返回局部变量,从 C 或 C++ 函数返回字符串的最佳方法是什么?

c++ - 错误 : Cannot add two pointers

C++ 无法让指针工作

c++ - 构造包含类型的参数

c++ - boost 文件系统错误(temp_directory_path 返回 <Bad Ptr>)

c - 在函数调用的参数内部定义新函数、数组、结构等