Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
May 12, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 <<"identical"<<endl;
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.
  • Danny Kalev
    Comment and Contribute






    (Maximum characters: 1200). You have 1200 characters left.



    Thanks for your registration, follow us on our social networks to keep up-to-date