I had a similar issue with C, but my problem now is actually more similar to this.
Unfortunately, I'm just learning C++, and I can't see how to apply the solution to my previous issue (if it indeed does apply), and the latter post was a specific problem with his code, that is more complex than my own.
Here is the relevant code:
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;
}
As you can see, p
and tmp
point to arrays that have initial sizes, and are freed within a few lines. Crucially, I cannot see how "a pointer being freed was not allocated" - p
is allocated on declaration, tmp
within the loop, then p
is freed and reallocated, then tmp
is freed, and so the loop continues...
I also tried implementing via two loops, but then the printed 'points' are (0, 0)
, whatever they actually are - I can't spot why?
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++;
}