Hello there!
Been breaking my head for couple of hours,the program i´m writing for a school asigment crashes every time when i try to compile it,and i have no clue why..
Hope someone out there can point out the error!
here is the relevant code:
1 2 3 4 5 6 7 8 9 10 11 12 13
class Graph
{
private:
int nroftowns;
int row;
int col;
string*Towns;
int**graph;
public:
Graph();
Graph(string cities[], int n);
void readFile();
Changed the code abit,program runs then crashes.
moved the line to the constructors this->Towns=new string[nroftowns]; från the fileread function,have initialized every member declared under private,have no clue whats causing it,something with memory alocation is my guess.
header:
1 2 3 4 5 6
private:
int nroftowns;
int row;
int col;
string*Towns;
int**graph;
This is going to crash. In your constructor, your nroftowns=0, which means no memory is allocated. Now in readFile(), you are doing:
this->Towns[i]=city;
as there is no memory allocated to Towns, it is going to crash. I suggest, read the correct values in the constructor only, make proper initialization of nroftowns, and than allocate correct memory and than work with Towns and other pointers.
Also, whenever you work with pointers, first check them if they are null before dereferencing them. With pointers you should always be sure that the index you are trying to access is actually available.
Edit:
so it should be something like this in constructor:
ifstream in;
in.open("citys.txt");
in>>n;
this->nroftowns=n; //see if you are getting correct value for n
//close the file here if its not going to be used further
//rest of the constructor
this->Towns=new string[nroftowns];
this->graph=newint*[nroftowns];
for(int i=0;i<nroftowns;i++)
{
this->graph[i]=newint[nroftowns];
}
for(int i=0;i<nroftowns;i++)
{
for(int j=0;j<nroftowns;i++)
{
graph[i][j]=-1;
}
}