c++ - 为什么打印 char* 给出的是字符串而不是地址?

标签 c++ string pointers

<分区>

我正在学习 C++ 的基础知识,但在尝试破译以下有关字符和指针的内容时总是碰壁。其中包括行注释,让我了解目前正在发生的事情。鉴于我有如下代码:

    using namespace std;
    int main()
    {
          //String literal is an array of chars
          //Array address gets assigned to a ptr of char
          char myletters[] = {'h','i'};
          char* lp = myletters;
          cout << *lp << endl;

          //Logically equivalent to above statements
          char* letters2 = "hi";
          cout << *letters2 << endl;

          //String literal turns into array of chars
          //Array of chars gets assigned to a ptr of chars 
          //Each ptr of chars gets stored into letters array
          char* letters[] = {"hi","hello"};
          cout << *letters << endl;   
    }

我的输出将是:

h
h
hi

我的问题是:当我用final cout打印*letters的内容时,为什么得到的是字符串“hi”,而不是“hi”的地址或“hi”中第一个字符的地址?我知道 cout 的第一个用途是打印一个 char,最后一个 cout 是打印一个 char*,但我仍然想知道为什么它打印完整的字符串而不是我通常期望的指针地址。

谢谢。

最佳答案

<<运算符对 char* 有特殊定义打印它引用的 C 字符串。

在你的例子中,*letterschar*类型(是字母 char*[] ,与 char** 相同)而不是 char作为*lp有。

关于c++ - 为什么打印 char* 给出的是字符串而不是地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36105317/

相关文章:

c++ - g++ 无法链接 OpenAL 库

c++ - 如何将 hash_map 与 char* 一起使用并进行字符串比较?

string - 从字符串中删除转义符,或 "how can I get\out of the way?"

c++ - 错误 : request for member (maybe you meant to use '->' ? ) 已经使用 '->'

c - "int *nums = {5, 2, 1, 4}"导致段错误

c - 将NULL分配给C中链表中的头节点

c++ - 在特定时间后唤醒线程

c++ - 为什么 FindWindowEx 找不到我所有的按钮?

string - 在 Lua 中将字符串中的所有字符变为小写

C++ L"whatever"-> wstring -> basic_string<T>