简体   繁体   中英

Replicating std::string::insert(int pos, char ch)

I'm trying to replicate std::string::insert method. Here's my code.

string& string::insert(int pos, char ch)
{
    int len = m_length; //the length of the current string
    resize(++m_length); //a method to resize the current string(char *) 
    char *p = m_data + pos; //a pointer to the string's insert position 
    for (int i = len-1; i >= 0; i--) { //shift characters to the right
        p[i+1] = p[i];
    }
    *p = ch; //assign the character to the insert position
    m_data[m_length] = '\0'; //finish the string
    return *this;
}

However, using the code, my app sometimes crashes while shifting characters to the right.

Can somebody point me what could be the problem and how to fix it?

Thank you very much in advance!

You're shifting too many characters. You only need to shift len - pos characters, not len characters.

And if you don't subtract 1 when initializing i , the loop will shift the existing null byte, so you don't need to add it separately at the end.

string& string::insert(int pos, char ch)
{
    int len = m_length; //the length of the current string
    resize(++m_length); //a method to resize the current string(char *) 
    char *p = m_data + pos; //a pointer to the string's insert position 
    for (int i = len - pos; i >= 0; i--) { //shift characters to the right
        p[i+1] = p[i];
    }
    *p = ch; //assign the character to the insert position
    return *this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM