My code simply reads problems from 42 different text files and solves them, and then prints out the solution.
I know it is not a good practice but I am using global variables such as
Customer *customers;
vector<int> *schedules;
double **distanceMatrix;
and suppose that I have to do this.
My problem appears while initializing distanceMatrix
:
distanceMatrix = new double*[n];
for (int i = 0; i<n; i++)
distanceMatrix[i] = new double[n];
The part that I could not understand is, I get a runtime error not in the first problem, not in the second, but at random problems between 9 and 25. Hence, I am pretty sure that files are well-formatted.
I do not have any syntax errors.
Sometimes, I get runtime error while reading from text file 9, sometimes 13, sometimes 22 etc.
I think there is some trick I am missing while initializing global variables. Maybe I need something like flush
.
What am I doing wrong?
I have also tried reading only one file at a time, not reading all the files with a loop. i.e. not initializing the global variables again and again. I had no runtime errors.
A minimal example:
vector<int> **trucks;
vector<int> **presellers;
Customer *customers;
Customer *sortedCustomers;
double **distances;
int type, m, n, t, D, Q;
int id;
void readFromFile(const char *prefix, int instanceId)
{
stringstream fileName;
id = instanceId;
fileName << prefix << instanceId << ".txt";
FILE *file = fopen(fileName.str().c_str(), "r");
fscanf(file, "%d %d %d %dn", &type, &m, &n, &t);
fscanf(file, "%d %dn", &D, &Q);
trucks = new vector<int> *[m];
presellers = new vector<int> *[m];
for (int i = 0; i<m; i++)
{
trucks[i] = new vector<int>[t];
presellers[i] = new vector<int>[t];
}
customers = new Customer[n];
sortedCustomers = new Customer[n];
distances = new double*[n];
for (int i = 0; i<n; i++)
distances[i] = new double[n];
int i, d, q, f, a;
float x, y;
fscanf(file, "%d %f %f %d %d %d %dn", &i, &x, &y, &d, &q, &f, &a);
createCustomer(i, x, y, d, q, f, a, t); // read depot
for (int j = 1; j<n + 1; j++) // read customers
{
fscanf(file, "%d %f %f %d %d %d %dn", &i, &x, &y, &d, &q, &f, &a);
createCustomer(i, x, y, d, q, f, a, t);
for (int k = 0; k<a; k++)
fscanf(file, "%d ", &(customers[j].list[k]));
}
for (int j = 0; j<n-1; j++) // compute distance matrix
for (int k = j + 1; k<n; k++)
computeDistance(j, k);
}
int main()
{
const char *inputPrefix = "t"; // prefix of the instance files.
int begin = 1;
int end = 42;
for (int i = begin; i <= end; i++)
{
readFromFile(inputPrefix, i); // read instance from file
}
system("pause");
return 0;
}
Inputs:
https://www.dropbox.com/s/kdchj1g3e13aic8/files.zip?dl=0
Aucun commentaire:
Enregistrer un commentaire