【发布时间】:2017-10-20 22:48:41
【问题描述】:
我正在尝试复制 std::string::insert 方法。 这是我的代码。
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;
}
但是,使用该代码时,我的应用有时会在将字符向右移动时崩溃。
谁能指出可能是什么问题以及如何解决它?
非常感谢您!
【问题讨论】:
-
如果这是你的实际代码,你的调整大小应该是
resize(m_length +1),否则你实际上将 m_length 增加了 1,这将导致m_data[m_length] = '\0';除了导致其他问题之外。虽然我需要看到resize才能确定... -
@Zack Lee This loop for (int i = len-1; i >= 0; i--) { //向右移动字符 p[i+1] = p[i] ; } 没有意义。您必须从该位置开始移动元素。那就是表达式 p + len 可以在字符串之外。