devxlogo

Using a string object in a context requiring a “read-only” char*

Using a string object in a context requiring a “read-only” char*

The advantages of a string object over a C-style char* are obvious. Yet there are times you may still need a null-terminated char*, for example, when legacy C code is still being used in your programs. The standard string class has the c_str() member function which returns the const char* representation of its object:

 void f() {string  s;s = "Hello";if( strcmp( s.c_str(), "Hello")== 0) //are they identical?cout 

Please note:

  • The const char* returned from the c_str() member function is owned by the string object, therefore, you should not attempt to delete it.
  • It points to a valid char* as long as you do not call any non-const member function of the string object.
  • devx-admin

    Share the Post: