0

我正在为一个动态的字符串数组创建一个容器类。我知道使用 std::vector 会更好,但这不是分配的“指针”。

据我所知,我的程序在下面的 delete [] lineArray 步骤中挂起。

MyBag::MyBag()
{
    nLines = 0;
    lineArray = new std::string[0] ();
}
void MyBag::ResizeArray(int newLength)
{
    std::string *newArray = new std::string[newLength];
    //create new array with new length
    for (int nIndex=0; nIndex < nLines; nIndex++)
    {
        newArray[nIndex] = lineArray[nIndex];
        //copy the old array into the new array
    }
    delete[] lineArray; //delete the old array
    lineArray = newArray; //point the old array to the new array
    nLines = newLength; //set new array size
}
void MyBag::add(std::string line)
{
    ResizeArray(nLines+1); //add one to the array size
    lineArray[nLines] = line; //add the new line to the now extended array
    nLines++;
}

整个程序在这里http://pastebin.com/KnL4XmAw

4

2 回答 2

3
ResizeArray(nLines+1); //add one to the array size
lineArray[nLines] = line; //add the new line to the now extended array
nLines++;

调用ResizeArray已经调整了 的值nLines。最后一行的增量是错误的,倒数第二行的使用也是错误的lineArray[nLines]

于 2013-05-13T18:22:52.420 回答
1

问题出在add

ResizeArray(nLines+1); //add one to the array size - INCREMENTS nLines
lineArray[nLines] = line; //add the new line AFTER THE END OF the now extended array
nLines++;                 //add another one to the array size - WRONG

这应该是:

ResizeArray(nLines+1); //add one to the array size
lineArray[nLines-1] = line; //add the new line to the now extended array

此外,如果您正在编写一个类来管理这样的动态资源,请确保您考虑了三法则。如果你复制它,你的会大错特错。

于 2013-05-13T18:23:59.160 回答