samedi 29 septembre 2018

Strange behavior when modifying string passed by reference

I have a function passing a string by reference and swapping two characters in it, but after the function call completes, the value of that string is different. At POINT A the value of s is "care", but at POINT B the value of s is "are". Can someone please explain why this is the case?

void func1() {
    string s = "acre";
    func2(s);
    //POINT B
}

void func2(string& s, string t) {
    int i = stoi(t.substr(2, 1));
    char c = s[i];
    s[i] = s[i + 1];
    s[i + 1] = c;
    //POINT A
}

Aucun commentaire:

Enregistrer un commentaire