My code is like this:
string s = "abc";
char* pc = const_cast<char*>( s.c_str() );
pc[ 1 ] = 'x';
cout << s << endl;
When I compiled the snippet above using GCC, I got the result "axc" as expected. My question is, is that safe and portable to modify the underlying char
array of a C++ string in this way? Or there might be alternative approaches to manipulate string's data directly?
FYI, my intention is to write some pure C functions that could be called both by C and C++, therefore, they can only accept char*
as arguments. From char*
to string, I know there is copying involved, the penalty is unfavorable. So, could anybody give some suggestions to deal with this sort of situation.
The obvious answer is no, it's undefined behavior. On the other hand, if you do:
you can access the underlying data, in practice today, and guaranteed in C++11.