【问题标题】:Why does the index of a `char **` type give the whole string?为什么 `char **` 类型的索引会给出整个字符串?
【发布时间】:2020-10-31 21:41:17
【问题描述】:

考虑一下这个sn-p:

#include <iostream>

using std::cout;
using std::endl;

int main()
{
    char c[] = {'a','b','c','\0'};
    char *pc = c;
    char **ppc = &pc;
    cout << ppc[0] << endl;
}

这将打印abc 作为输出。为什么指向char 的指针的索引会返回整个字符串?这里,ppc 只指向另一个指向单个char 的指针。它如何知道整个字符串以及为什么要返回它?

【问题讨论】:

    标签: c++11 pointers char


    【解决方案1】:

    您必须了解std::cout 是什么以及为什么它将char* 视为“字符串”。

    开始吧:

    std::coutstd::ostream 的一个实例,std::ostream 有很多运算符。什么意思?

    std::ostream的实现可以,但这里只是作为例子,写成这样:

     class ostream
     {
         // ... a lot more code for constructors and others
         ostream& operator <<( const int );
         ostream& operator <<( const double );
         ostream& operator <<( char* );        <<< this is the implementation you search for!
         // a long list of more special overloads follow
     };
    

    而实现只是简单地输出 char* 指向的“字符串”。

    您看到的只是 operator&lt;&lt;std::ostream 类的特殊重载。

    好的,真正的实现使用非成员重载,但这对于理解std::ostream 的原理并不重要。

    更多详情见:std::ostream::operator<<()

    字符和字符串参数(例如,char 或 const char* 类型)由 operator

    【讨论】:

    • 啊,我明白了!太感谢了! :)
    【解决方案2】:

    这些是等价的:

    cout << ppc[0] << endl;
    cout << *( ppc + 0 ) << endl;
    cout << *ppc << endl;
    cout << *(&pc) << endl;
    cout << pc << endl;
    

    【讨论】:

    • 谢谢!但这让我意识到我困惑的根源在于为什么打印 pc 会打印整个字符串;指向char 的指针是否以某种方式被视为字符串?
    • 是的,因为char* 指针经常用于(NUL 终止的)字符串。这来自 C++ 的 C 遗产。
    猜你喜欢
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 2014-03-30
    • 2019-01-09
    • 1970-01-01
    • 2018-10-30
    相关资源
    最近更新 更多