If you just want to pass a std::string to a function, then you can use the below expression.
//Example
std::string str;
const char * c = str.c_str();
If you want to get a writable copy, like char *, you can do that with this:
std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;
NoteThe above code is not exception-safe.
We can also do it with std::vector, it completely manages the memory for you.
std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');
// get the char* using &writable[0] or &*writable.begin()
Answer:
If you just want to pass a std::string to a function, then you can use the below expression.
If you want to get a writable copy, like char *, you can do that with this:
NoteThe above code is not exception-safe.
We can also do it with std::vector, it completely manages the memory for you.
need an explanation for this answer? contact us directly to get an explanation for this answer