when I use strtok to tokenize a c++ string, it happens a confusing problem, see the simple code below:
void a(string s){
strtok((char*)s.c_str(), " ");
}
int main(){
string s;
s = "world hello";
a(s);
cout<<s<<endl;
return 0;
}
the program outputs “world”.
Shouldn’t it output “world hello”? Because I pass the string as a value parameter to function a, the strtok shouldn’t modify the original s…
Can anyone explain this trick.
thank you.
The problem is
(char*)s.c_str(), you are casting the constness away and modified thestringcontents in a way that you are not supposed to. While the originalsshould not be modified, I pressume you may have been hit by a smart optimization that expects you to play by the rules. For instance, a COW implementation ofstringwould happen to show that behavior.