To obtain a const char *
from an std::string
use the c_str()
member function :
std::string str = "string";
const char* chr = str.c_str();
To obtain a non-const char *
from an std::string
you can use the data()
member function which returns a non-const pointer since C++17 :
std::string str = "string";
char* chr = str.data();
For older versions of the language, you can use range construction to copy the string into a vector from which a non-const pointer can be obtained :
std::string str = "string";
std::vector<char> str_copy(str.c_str(), str.c_str() + str.size() + 1);
char* chr = str_copy.data();
But beware that this won't let you modify the string contained in str
, only the copy's data can be changed this way. Note that it's specially important in older versions of the language to use c_str()
here because back then std::string
wasn't guaranteed to be null terminated until c_str()
was called.