0
char *m_chString="asd"; 
cout<<m_chString;//prints asd
cout<<*m_chString;//prints a


int nValue = 7;
int *pnPtr = &nValue;
cout<<*pnPtr;//prints 7
cout<<pnPtr;//prints the address of nValue

I gave two examples, in the first the pointer points to a string, and in the second, the pointer prints to an int value.
My question is, why cout<<m_chString; from the first example doesn't print the address of my string as it would do in the second example if I were to print pnPtr without dereferencing it?
Doesn't pnPtr point to an address?

Baldrickk
  • 4,291
  • 1
  • 15
  • 27
George Irimiciuc
  • 4,573
  • 8
  • 44
  • 88

1 Answers1

2

The reason for that is that std::cout will treat a char * as a pointer to (the first character of) a C-style string and print it as such.

You can print the address by:-

    cout << (void *) m_chString;

OR if you are great C++ fan then

    cout << static_cast <const void *> (m_chString);
ravi
  • 10,994
  • 1
  • 18
  • 36
  • +1 since the general idea is right, but you might want to clarify that it's not `std::cout` itself doing this. It's the overload of `operator<<` which works for all output streams, not just `cout`. – Angew is no longer proud of SO Oct 28 '14 at 08:22
  • If it points to the first character, then why doesn't it print only that one and it prints the whole string? – George Irimiciuc Oct 28 '14 at 08:22
  • @Angew yes agree with you. – ravi Oct 28 '14 at 08:25
  • @GeorgeIrimiciuc Please see Angew's explanation. – ravi Oct 28 '14 at 08:26
  • @GeorgeIrimiciuc Because whoever designed the streams library decided it was more useful to treat `char*` as a pointer to a null-terminated string and print the whole string. – juanchopanza Oct 28 '14 at 08:26
  • @GeorgeIrimiciuc Bracketing in the sentence. It treats it as a pointer to the first character of (a C-style string and prints it as such). Simply put: it's designed for printing strings. – Angew is no longer proud of SO Oct 28 '14 at 08:26
  • I see. The thing is if I do `cout<<&m_chString;` it will print the address, too. Why do I need to cast it to void*, then? – George Irimiciuc Oct 28 '14 at 08:28
  • @GeorgeIrimiciuc: With `cout<<&m_chString;`, you're printing the address of the pointer, which is completely different from the value of the pointer (that is, the address of the thing the pointer points to). If you print both `&m_chString` and `(void*)m_chString`, you should see different values. – Benjamin Lindley Oct 28 '14 at 08:32