正在释放的指针未被分配,动态数组C++

OJF*_*ord 1 c++ arrays pointers memory-management dynamic-arrays

和C有类似的问题,但我现在的问题实际上与此类似.

不幸的是,我只是在学习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;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,ptmp指向具有初始大小的数组,并在几行内释放.至关重要的是,我看不出"释放的指针是如何被分配的" - 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++;
}
Run Code Online (Sandbox Code Playgroud)

bar*_*nos 8

这里几乎每一行都有一个错误:

point *p = new point[1]; // Allocation #1
tmp = new point[pcount]; // Allocation #2
tmp = p;                 // Allocation #2 lost (memory leak)
delete [] p;             // Now 'tmp' is "pointing to junk"
p = new point[pcount];   // Allocation #3
p = tmp;                 // Allocation #3 lost (memory leak), and 'p' is "pointing to junk"
delete [] tmp;           // Segmentation fault, since 'tmp' is "pointing to junk"
p[pcount-1].x = n1;      // Segmentation fault, since 'p' is "pointing to junk"
p[pcount-1].y = n2;      // Segmentation fault, since 'p' is "pointing to junk"
Run Code Online (Sandbox Code Playgroud)