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;
}
然而,使用代碼,我的應用程序有時在換擋字符向右崩潰。
有人可以指出我可能是什麼問題,以及如何解決它?
非常感謝您提前!
創建[MCVE] – user2079303
如果這是你的實際代碼,您的調整大小應該是'調整(m_length +1)',否則,你實際上是增加了1 m_length這將炸燬'M_DATA [m_length] = '\ 0';'除了導致其他問題。雖然我需要看到'resize'知道肯定... – zzxyz
@Zack Lee這個循環(int i = len-1; i> = 0; i--){//將字符右移 p [i + 1] = p [i]; }沒有意義。你必須從這個位置開始轉移元素。那就是表達式p + len可以在字符串之外。 –