So I have a header file and cpp file which contain this struct named 'Point' along with these already made working functions...
struct Point{
double x;
double y;
double z;
};t
Point* createPoint(double x, double y, double z);
void displayPoint(Point* p);
void destroyPoint(Point* p);
I am attempting now to create a header and cpp for "Points" with the struct below...
struct Points{
Point** array;
int pointsSize;
};
Whenever I implement the similar functions for "Point" but for "Points", It creates it perfectly. The first function that I call beyond creating it works perfectly too, but after that first function after creating Points, It messes up. My theory is that in my implementation of displayPoints (destroyPoints is the same for test purposes) is actually deleting the values after it gets off the stack.
Points* createPoints (const char* filename){
double x, y, z;
std::ifstream inFile;
inFile.open(filename);
Points p;
inFile >> p.pointsSize;
p.array = new Point*[p.pointsSize];
for(int i=0; i<p.pointsSize; i++){
inFile >> x;
inFile >> y;
inFile >> z;
p.array[i] = createPoint (x,y,z);
}
Points* ptr = &p;
return ptr;
}
// ERROR MUST BE DELETING POINTS
void displayPoints (Points* p){
Points n = *p;
int size = n.pointsSize;
Point** a = n.array;
for(int i=0; i<size; i++){
std::cout<<"Displaying Point "<<i<<"..."<<std::endl;
displayPoint(a[i]);
}
}
void destroyPoints (Points* p){
Points n = *p;
int size = n.pointsSize;
Point** a = n.array;
for(int i=0; i<size; i++){
std::cout<<"Displaying Point "<<i<<"..."<<std::endl;
displayPoint(a[i]);
}
}
Points* ptr = &p;
creates a pointer to a local variable.return ptr;
returns a dangling pointer (asp
goes out of scope and is destroyed) – UnholySheep Oct 27 '18 at 16:37std::vector<Points>
and 2) Passing by reference. – Thomas Matthews Oct 27 '18 at 17:14