Output C style string with std::cout

I tried this code
1
2
3
4
    string str="abcde";
    const char* c_str;
    c_str=str.c_str();
    cout<<c_str;


and it puts "abcde" on the output. I expected it to write out the address c_str points to. The c_str is a pointer so why does it return the letters?
<< is overloaded to treat const char* as string data rather than a pointer. It is done this way so that string literals (such as "example") get printed as text rather than addresses.

If you want to print the address, you'll have to cast the pointer to something else. void* is typical:

1
2
3
4
5
6
7
8
9
10
cout << static_cast<const void*>(c_str);

// or if you don't mind C style casting

cout << (const void*)(c_str);

// or... you could use const void from the start and avoid any casting:

const void* c_str = str.c_str();
cout << c_str;
Topic archived. No new replies allowed.