Conversion to const char

suggest change

In order to get const char* access to the data of a std::string you can use the string’s c_str() member function. Keep in mind that the pointer is only valid as long as the std::string object is within scope and remains unchanged, that means that only const methods may be called on the object.

The data() member function can be used to obtain a modifiable char*, which can be used to manipulate the std::string object’s data.

A modifiable char* can also be obtained by taking the address of the first character: &s[0]. Within C++11, this is guaranteed to yield a well-formed, null-terminated string. Note that &s[0] is well-formed even if s is empty, whereas &s.front() is undefined if s is empty.

std::string str("This is a string.");
const char* cstr = str.c_str(); // cstr points to: "This is a string.\0"
const char* data = str.data();  // data points to: "This is a string.\0"

std::string str("This is a string.");

// Copy the contents of str to untie lifetime from the std::string object
std::unique_ptr<char []> cstr = std::make_unique<char[]>(str.size() + 1);

// Alternative to the line above (no exception safety):
// char* cstr_unsafe = new char[str.size() + 1];

std::copy(str.data(), str.data() + str.size(), cstr);
cstr[str.size()] = '\0'; // A null-terminator needs to be added

// delete[] cstr_unsafe;
std::cout << cstr.get();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::string:
* Conversion to const char

Table Of Contents
8 Arrays
11 Loops
20 std::string
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype