Can I get a non-const C string back from a C++ string?

C++17 and newer:

foo(s.data(), s.size());

C++11, C++14:

foo(&s[0], s.size());

However this needs a note of caution: The result of &s[0]/s.data()/s.c_str() is only guaranteed to be valid until any member function is invoked that might change the string. So you should not store the result of these operations anywhere. The safest is to be done with them at the end of the full expression, as my examples do.


Pre C++-11 answer:

Since for to me inexplicable reasons nobody answered this the way I do now, and since other questions are now being closed pointing to this one, I’ll add this here, even though coming a year too late will mean that it hangs at the very bottom of the pile…


With C++03, std::string isn’t guaranteed to store its characters in a contiguous piece of memory, and the result of c_str() doesn’t need to point to the string’s internal buffer, so the only way guaranteed to work is this:

std::vector<char> buffer(s.begin(), s.end());
foo(&buffer[0], buffer.size());
s.assign(buffer.begin(), buffer.end());

This is no longer true in C++11.

Leave a Comment

tech