1

I'm studying pointer and got confused with c_str() function.

The description says it returns a constant Null terminated pointer to the character array and when i try to print the variable, it doesn't print the address of it.

int main() {
    string a = "hello";
    const char* b = a.c_str();
    cout << b << endl; //hello
}

I expected the output to be the address of b but instead it prints "hello".

Can someone explain why?

PolarBear
  • 29
  • 3

1 Answers1

7

There's an overload of operator<< for std::ostream and const char*, that will print the string rather than the pointer value (address).

You can cast to const void* to invoke the overload that prints the address.

cout << static_cast<const void*>(b);
Brian Bi
  • 111,498
  • 10
  • 176
  • 312