gpt4 book ai didi

c++ - Seg Fault Error C++,创建二维动态数组时

转载 作者:行者123 更新时间:2023-11-28 02:50:46 24 4
gpt4 key购买 nike

我正在创建一个二维动态数组来表示有向图。我将所有值设置为 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;}

最佳答案

您在此 block 中创建一个新的本地 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;

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

关于c++ - Seg Fault Error C++,创建二维动态数组时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23122264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com