Search code examples
c++pointersc-stringscoutmemory-address

C++ pointer with c-style string


Why i don't get the address when cout the pointer ? See the code below: code1:

string s1 {"NAME"};
string *p1 {&s1};
cout<<p1; 

gives 0x71fcc0 which makes sense. But see what happens when i use cstyle string:

char cstring1 [] {"NAME"};
char *cp2 = &cstring1[0];
cout<<cp2<<endl; 

Prints NAME on the screen So why it doesn't print an address ?


Solution

  • So why it doesn't print an address ?

    Because it is a pointer to char. And pointers to chars are treated differently from other pointers when inserted into a character stream.

    When pointer to char is inserted into a character stream, the pointed string is produced, rather than the address. If the pointed string is not null terminated, then behaviour of the program is undefined.