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.
data() member function can be used to obtain a modifiable
char*, which can be used to manipulate the
std::string object's data.
char* can also be obtained by taking the address of the first character:
&s. Within C++11, this is guaranteed to yield a well-formed, null-terminated string. Note that
&s 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();