【发布时间】:2014-02-23 12:43:44
【问题描述】:
我有a similar issue with C,但我现在的问题实际上是more similar to this.
不幸的是,我只是在学习 C++,我看不到如何将解决方案应用于我之前的问题(如果确实适用的话),而后一个帖子是他的代码的一个特定问题,那就是更多比我自己复杂。
以下是相关代码:
double n1, n2; //temporary data for user entry
int pcount = 0; //size of my array
struct point{double x; double y;};
point *p = new point[1]; //my array
point *tmp; //temporary array while resizing
while (points >> n1 >> n2){ //for each element the user enters,
pcount++; //increase the array size
tmp = new point[pcount]; //allocate new memory for the array
tmp = p; //copy the elements from the old to the temporary
delete [] p; //delete the old array
p = new point[pcount]; //allocate memory for the new array
p = tmp; //copy the elements from the temporary to the new array
delete [] tmp; //delete the temporary
p[pcount-1].x = n1; //now push back the new element
p[pcount-1].y = n2;
}
如您所见,p 和tmp 指向具有初始大小并在几行内释放的数组。至关重要的是,我看不到“未分配被释放的指针”-p 在声明时分配,tmp 在循环内,然后p 被释放并重新分配,然后tmp 被释放,所以循环继续...
我也尝试通过两个循环来实现,但是打印的“点”是(0, 0),不管它们实际上是什么 - 我不知道为什么?
while (points >> n1 >> n2){
pcount++;
}
p = new point[pcount];
int i = 0;
while (points >> n1 >> n2){
p[i].x = n1;
p[i].y = n2;
i++;
}
【问题讨论】:
-
A) 你有内存泄漏,B) 你重复删除了一些东西,C) 省去你的痛苦并使用
std::vector -
为什么不分两遍来做呢?首先计算你需要多少点,然后只分配一个点数组?无需处理两个指针和更少的内存碎片。
-
tmp = new point[pcount]; tmp = p;- 如果你立即分配给tmp别的东西,第一个分配有什么意义? -
@Borgleader 这是一项未经评估的实验室任务,它注意到
std::vector的存在,但目标是使用和理解动态数组,new,delete []。 -
@JHagdahl 我最初尝试过,尽管它不是实验室工作表上列出的方法 - 在我看来,这更有效,因为更少的内存访问。但是,我遇到了这个错误/段错误 11,所以我决定按照表格进行操作。
标签: c++ arrays pointers memory-management dynamic-arrays