Why does the index of a `char **` type give the whole string?

前端 未结 2 712
天命终不由人
天命终不由人 2021-01-27 09:14

Consider this snippet:

#include 

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

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


        
相关标签:
2条回答
  • 2021-01-27 09:29

    These are equivalent:

    cout << ppc[0] << endl;
    cout << *( ppc + 0 ) << endl;
    cout << *ppc << endl;
    cout << *(&pc) << endl;
    cout << pc << endl;
    
    0 讨论(0)
  • 2021-01-27 09:37

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

    Lets start:

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

    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
     };
    

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

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

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

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

    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.

    0 讨论(0)
提交回复
热议问题