为什么`char **`类型的索引给出整个字符串? [英] Why does the index of a `char **` type give the whole string?

查看:65
本文介绍了为什么`char **`类型的索引给出整个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

#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 的指针.它如何得知整个字符串以及为什么要返回它?

This prints abc as output. Why does the index of a pointer to pointer to char return the whole string? Here, ppc only points to another pointer that points to a single char. How does it know about the whole string and why would it return it?

推荐答案

您必须了解 std :: cout 是什么以及为什么将 char * 视为字符串".

You have to understand what std::cout is and why it treats a char* as a "string".

让我们开始吧:

std :: cout std :: ostream 的一个实例,而 std :: ostream 具有很多运算符.是什么意思?

std::cout is an instance of an std::ostream and std::ostream has a lot of operators. What does it mean?

std :: ostream 的实现可以(但仅作为示例)编写如下:

The implementation of std::ostream can, but only as an example here, written like:

 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 *指向的位置.

And the implementation simply puts out the "string" which the char* points to.

您看到的只是 std :: ostream 类的 operator<< 的特殊重载.

What you see is simply a special overload of the operator<< for the std::ostream class.

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

OK, the real implementation uses a non-member overload, but that is not important for understanding how std::ostream works in principal.

有关更多详细信息,请参见: std :: ostream :: operator<<()

For more details see: std::ostream::operator<<()

字符和字符串参数(例如char或const char *类型)由operator <<的非成员重载处理.尝试使用成员函数调用语法(例如std :: cout.operator<<('c');)输出字符将调用重载(2-4)之一并输出数值.尝试使用成员函数调用语法输出字符串将调用重载(7)并打印指针值.

Character and character string arguments (e.g., of type char or const char*) are handled by the non-member overloads of operator<<. Attempting to output a character using the member function call syntax (e.g., std::cout.operator<<('c');) will call one of overloads (2-4) and output the numerical value. Attempting to output a character string using the member function call syntax will call overload (7) and print the pointer value instead.

这篇关于为什么`char **`类型的索引给出整个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆