2

I'm going through the basics of learning C++, but keep hitting a wall when trying to decipher the following about chars and pointers. Included are line comments giving my current understanding of what's going on. Given that I have code like below:

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

My output will be:

h
h
hi

My question is: when I use the final cout to print the contents of *letters, why do I get the string "hi" rather than the address of "hi" or the address of the first character in "hi"? I get that the first uses of cout are printing a char, and that the last cout is printing a char*, but I'm still wondering why it prints the complete string rather than the address as I would generally expect from a pointer.

Thanks kindly.

Joefers
  • 97
  • 7

1 Answers1

0

the << operator has a special definition for char* that prints the C-string it refers.

In your case, *letters has char* type (being letters a char*[], same as char**) and not char as *lp have.

Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
  • 1
    I would add that to print the adress, you just have to cast to a `void*` so that the overload for `const char *` is not used anymore: `cout << static_cast(*letters) << endl;` – Colin Pitrat Mar 19 '16 at 18:37