1

我正在分配为动态字符串数组创建一个容器类。我知道使用 std::vector 会更容易/更好,但这不是重点。我在找到在构造函数中初始化数组的正确方法时遇到问题。下面的方式,编译器仍然警告我没有使用变量 lineArray。程序编译时会发出警告,即 lineArray 未使用,然后在运行时挂起。

MyBag::MyBag()
{
    nLines = 0;
    std::string 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://ideone.com/pxX18m

4

4 回答 4

1

除了编译器报告的明显错误(即初始化局部变量而不是分配给实例变量)之外,您还有一个更严重的问题:如果传递给的值nLines小于ResizeArray分配区域的结束。您需要按如下方式更改代码:

void MyBag::ResizeArray(int newLength)
{
    // Add a trivial optimization:
    if (newLength == nLines) {
        // No need to resize - the desired size is already set
        return;
    }
    std::string *newArray = new std::string[newLength];
    //create new array with new length
    for (int nIndex=0; nIndex < nLines && nIndex < newLength ; 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
}
于 2013-05-10T17:16:04.500 回答
1

警告救援。幸好你有编译器警告,否则这将是一个需要更长时间才能弄清楚的错误。

std::string lineArray = new std::string[0] ();
^^^^^^^^^^^

正在声明一个在构造函数中调用的新变量。lineArray您没有使用班级成员一。成员lineArray指针仍将指向一些未初始化的内存。


它应该是

lineArray = new std::string[0] ();
于 2013-05-10T17:12:01.270 回答
1

lineArray您正在使用在构造函数中调用的局部变量。您想使用您的数据成员,例如:

MyBag::MyBag()
{
    nLines = 0;
    lineArray = new std::string[0] ();
}
于 2013-05-10T17:12:10.897 回答
1

除了阴影成员变量和ResizeArray较小的数组问题之外,您的方法中还有一个错误add(),如 6602 所示。在您调用 之后ResizeArraynLines已经将其更新为新值,因此您实际上是写错了数组位置,然后nLines再次错误地递增。确保写入正确的位置,无需增加。

void MyBag::add(std::string line)
{
    int oldLength = nLines;
    ResizeArray(nLines+1); //add one to the array size
    lineArray[oldLength] = line; //add the new line to the now extended array
}
于 2013-05-10T17:31:12.043 回答