string.c_str() is const?

c++

Solution

Nothing.

Because `std::string` manages itself its contents, you can't have write access to the string's underlying data. That's undefined behavior.

However, creating and copying a char array is not hard:

std::string original("text");
std::vector<char> char_array(original.begin(), original.end());
char_array.push_back(0);

some_function(&char_array[0]);

Problem

I have a function in a library that takes in a `char*` and modifies the data. I tried to give it the `c_str()` but c++ docs say it returns a `const char*`. What can I do other than newing a char array and copying it into that?

Original source

Related problems