Question

This code:

string  str1 ( "Hello world" );
const char *c_str1 = str1.c_str ( );
cout << "The C-style string c_str1 is: " << c_str1 

generates this output:

The C-style string c_str1 is: Hello world

and I do not understand it.

c_str1 is a pointer, right? So, c_str1 should return an address and only *c_str1 should give the value located at this address. However, in the above example c_str1 gives the value (not the address).

What do I misunderstand?

Était-ce utile?

La solution

It's because of how std::cout::operator << is defined - it has an overload that takes a const char* and prints the string it points to. If you want the address, you'll have to cast to void*.

Autres conseils

"What do I misunderstand?" The definition of << on a char const*. The pointer is passed by value, but the definition of operator<<( std::ostream&, char const* ) specifies that it treat the pointer as the start of a '\0' terminated string.

The variable c_str1 is a pointer to the first character in the string. &c_str1 is a pointer to c_str1 (i.e. a pointer to a pointer). *c_str1 is the value at the location pointed to by c_str1 (i.e. only a single character).

The output operator has an overload that takes a pointer to a character (what c_str1 is) and prints it as a string.

The standard specifies overloads of operator<< (ostream, char*) which output the string stored in the pointer. In other words, c_str1 is indeed a pointer, but the output stream is interpreting it as the string it points to.

To output the pointer value, cast it to void*:

cout << "The C-style string c_str1 is: " << static_cast<void*>(c_str1);

There is an overload of ostream& operator<< for const char*, which assumes the pointer points to the first character in a null terminated string, and prints the whole string.

You can see an example of this assumption being applied somewhere it shouldn't here:

#include <iostream>

int main()
{
  char c = 'x'; // not a null terminated string
  std::cout << &c << std::endl; // will write until it finds a 0 (really UB)
}

The cout operator<< interprets pointers to char as C-strings.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top