2017-10-20 70 views
0

我試圖複製std :: string :: insert方法。 這是我的代碼。複製std :: string :: insert(int pos,char ch)

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; 
} 

然而,使用代碼,我的應用程序有時在換擋字符向右崩潰。

有人可以指出我可能是什麼問題,以及如何解決它?

非常感謝您提前!

+1

創建[MCVE] – user2079303

+0

如果這是你的實際代碼,您的調整大小應該是'調整(m_length +1)',否則,你實際上是增加了1 m_length這將炸燬'M_DATA [m_length] = '\ 0';'除了導致其他問題。雖然我需要看到'resize'知道肯定... – zzxyz

+1

@Zack Lee這個循環(int i = len-1; i> = 0; i--){//將字符右移 p [i + 1] = p [i]; }沒有意義。你必須從這個位置開始轉移元素。那就是表達式p + len可以在字符串之外。 –

回答

1

您正在轉換太多字符。您只需要移動len - pos個字符,而不是len個字符。

如果初始化i當你不減去1,循環將轉向現有的空字節,所以你不需要在最後單獨添加它。

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; 
} 
+0

這完全解決了這個問題。非常感謝你@Barmar –

相關問題