【发布时间】:2014-04-16 23:54:34
【问题描述】:
我正在创建一个二维动态数组以表示有向图。我将所有值设置为 false。然后,当我从文件中获取数据时,我将适当的行/列组合设置为 true,以表示该行具有朝向该列的定向边缘。但是,我遇到了段错误。我想知道是否有人可以帮助我弄清楚如何解决段错误,所有帮助将不胜感激。我的代码如下。
#include <iostream>
#include <fstream>
#include <cstdio>
#include <sstream>
using namespace std;
class Graph{
public:
string nodes;
bool **A;
};
int main(int argc, char** argv) {
if (argc != 2) {
cout << "No file was given as an argument, and the program will end now." << endl;
return 0; }
ifstream graph ( argv[1]);
Graph myGraph;//graph object
string num;
int tempNum;
int tempNum2;
int tracker = 0;
while (graph.good())
{
graph >> num ;
if( tracker == 0) {// if first number then create array
myGraph.nodes = num;
myGraph.A = new bool * [tempNum];
int i, m, n;
for (i = 0; i < tempNum; i++ ){
myGraph.A[i] = new bool [tempNum];
}
//set all to false
for (m = 0; m < tempNum; m++) {
for(n = 0; n < tempNum; n++){
myGraph.A[n][m] = false; }}
tracker++;}//end of if tracker = 0
else {//otherwise make connection true in 2d array
if(tracker % 2 == 1){
stringstream convert(num);
int tempNum;
convert >> tempNum;
tracker++;
}
else if(tracker % 2 == 0) {
stringstream convert(num);
int tempNum2;
convert >> tempNum2;
myGraph.A[tempNum][tempNum2] = true;
tracker++;
}
}
}//end of while
cout << myGraph.A[5][5] << "should be false " << false << endl;
cout << myGraph.A[3][2] << "should be false " << false << endl;
cout << myGraph.A[4][6] << "should be false " << false << endl;
cout << myGraph.A[8][9] << "should be true: " << true << endl;
cout << myGraph.A[7][5] << "should be true: " << true << endl;
cout << myGraph.A[2][4] << "should be true: " << true << endl;
graph.close();
return 0;}
【问题讨论】: