我正在分配为动态字符串数组创建容器类。我知道使用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++;
}
答案 0 :(得分:1)
警告救援。你有编译器警告的好事,否则这将是一个需要更长时间才能搞清楚的错误。
std::string lineArray = new std::string[0] ();
^^^^^^^^^^^
在构造函数中声明了一个名为lineArray
的新变量。您没有使用类成员之一。成员lineArray
指针仍将指向某些未初始化的内存。
应该是
lineArray = new std::string[0] ();
答案 1 :(得分:1)
您正在构造函数中使用名为lineArray
的局部变量。您想使用您的数据成员,例如:
MyBag::MyBag()
{
nLines = 0;
lineArray = new std::string[0] ();
}
答案 2 :(得分:1)
除了编译器报告的明显错误(即初始化局部变量而不是分配给实例变量)之外,还有一个更严重的问题:如果将小于nLines
的值传递给{{1}通过将数据写入已分配区域的末尾,您的代码将显示未定义的行为。您需要按如下方式更改代码:
ResizeArray
答案 3 :(得分:1)
除了阴影成员变量和ResizeArray
到更小的数组问题之外,您的add()
方法存在错误,如6602所示。致电ResizeArray
后,nLines
已经更新为新值,因此您实际上写入错误的数组位置,然后再次错误地递增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
}