Seg Fault Error C ++,创建2d动态数组时

时间:2014-04-16 23:54:35

标签: c++ arrays dynamic graph

我正在创建一个2d动态数组,以表示有向图。我将所有值设置为false。然后,当我从文件中获取数据时,我将相应的行/列组合设置为true,以表示该行具有朝向列的有向边。但是,我遇到了一个段错误。我想知道是否有人可以帮我弄清楚如何修复seg故障,所有的帮助将不胜感激。我的代码如下。

 #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;}

2 个答案:

答案 0 :(得分:1)

以下是一些观察结果:

  • tempNumif (tracker == 0)分支中使用之前未初始化。所以2d数组分配大小是未定义的。
  • 此外,int tempNum分支中的声明if (tracker %2 == 1)会在while (graph.good())循环开始之前影响早期声明。在分支结束时,此声明不再有效,因此获得的值不会在if (tracker % 2 == 0))分支中使用。

答案 1 :(得分:1)

您在此块中创建一个新的本地tempNum变量:

    if(tracker % 2 == 1){
        stringstream convert(num);
        int tempNum;                  // <<<<<<<<<<<<
        convert >> tempNum;
        tracker++;
        }

它将影响前面宣布的那个:

int tempNum;                          // <<<<<<<<<<<<
int tempNum2;
int tracker = 0;

因此,这里的第一个索引将是未定义的(原始变量再次,但尚未分配):

    myGraph.A[tempNum][tempNum2] = true;

这会导致内存访问冲突和崩溃。