【发布时间】:2016-04-10 23:58:10
【问题描述】:
我有一个指向 Airport 对象的类。动态数组的大小从 10 开始。当total 大于数组的大小并且我已读入数据以填充数组时,我需要将数组的大小加倍,从旧数组放入新大小的数组,然后删除旧数组。该数组将继续读入数据,然后调整大小,并继续此操作,直到文件中的所有数据都读入items 数组。
没有发生错误,但问题是当我运行程序时,它崩溃了。我认为我的doubleSize 调整数组大小的函数可能是造成这种情况的原因。有没有办法解决这个问题?
class AirportList
{
private:
Airport* items;
int total;
int maxElements;
int oldAmount;
public:
AirportList()
{
oldAmount = 10;
maxElements = 10;
items = new Aiport[maxElements];
// a file was opened to read in data before this,
// total equals the total amount of lines in the file
string cppstr;
for (int counter = 0; counter < total; counter++)
{
getline(infile, cppstr);
items[counter] = Airport(cppstr); // the Airport constructor
// parses each line to read in
// the data and sets each Airport
// object into the items array
if (total > maxElements && counter == maxElements)
doubleSize(items, maxElements, oldAmount);
}
infile.close();
}
void doubleSize(Airport*& orig, int maxElements, int oldAmount)
{
maxElements = maxElements * 2;
Aiport* resized = new Aiport[maxElements];
for (int i = 0; i < oldAmount; i++)
resized[i] = orig[i];
delete [] orig;
orig = resized;
oldAmount = maxElements;
}
};
【问题讨论】:
-
` 我认为我的 doubleSize 函数调整数组大小可能是造成这种情况的原因` 好吧调试它并确认是这种情况!第一个明显的问题:
doubleSize的oldAmount参数是否应该是参考?如果没有,则将其设置在最后一行不会执行任何操作。 (maxElements同上。我认为必须是参考,oldAmount不是那么重要。 -
@John3136 我试过调试它,但我还是调试新手,所以很遗憾我找不到导致崩溃的原因。
-
你可以通过打印出值来调试,看看你的程序能走多远以及它在不同点的状态是什么。
-
代码不正确。您必须将数组声明为
Airport ** items
标签: c++ arrays pointers dynamic