I am trying to write a function that returns an array of struct in c++. I seem to be able to fill the array from an input file. However, I run into segmentation fault upon returning the struct array. Am I missing something?
Coordinates* GetCoordinates(string Input) {
Coordinates* coor_array = new Coordinates[1000];
int k = -1;
string line;
ifstream file;
file.open(Input.c_str());
while (!file.eof()){
getline(file,line);
k++;
char** holder = split (line,' ');
coor_array[k].element = holder[0];
coor_array[k].x = atof(holder[1]);
coor_array[k].y = atof(holder[2]);
coor_array[k].z = atof(holder[3]);
cout << "Atom:" << coor_array[k].element << " X:" << coor_array[k].x << " Y:" << coor_array[k].y << " Z:" << coor_array[k].z <<endl;
}
return coor_array;
}
While my struct definition is below:
struct Coordinates
{
string element;
double x,y,z;
};
I use the following to call my function:
Coordinates* coor_data = GetCoordinates(Input);
Upon running, I get the following error:
Atom:H X:26.4706 Y:30.0098 Z:64.4696
Atom:O X:25.8063 Y:28.7746 Z:64.7809
Atom:H X:25.6821 Y:30.626 Z:63.3106
Segmentation fault
Could anyone suggest what could be the problem?