C++ Seg故障错误C++;,创建二维动态阵列时
为了表示有向图,我正在创建一个2d动态数组。我将所有值都设置为false。然后,当我从文件中获取数据时,我将适当的行/列组合设置为true,以表示该行具有指向该列的定向边。但是,我遇到了seg故障。我想知道是否有人能帮我找出如何修复seg故障,所有的帮助都将不胜感激。我的代码如下C++ Seg故障错误C++;,创建二维动态阵列时,c++,arrays,dynamic,graph,C++,Arrays,Dynamic,Graph,为了表示有向图,我正在创建一个2d动态数组。我将所有值都设置为false。然后,当我从文件中获取数据时,我将适当的行/列组合设置为true,以表示该行具有指向该列的定向边。但是,我遇到了seg故障。我想知道是否有人能帮我找出如何修复seg故障,所有的帮助都将不胜感激。我的代码如下 #include <iostream> #include <fstream> #include <cstdio> #include <sstream> using na
#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;}
#包括
#包括
#包括
#包括
使用名称空间std;
类图{
公众:
字符串节点;
布尔**A;
};
int main(int argc,字符**argv){
如果(argc!=2){
库特数;
如果(tracker==0){//如果是第一个数字,则创建数组
myGraph.nodes=num;
myGraph.A=新bool*[tempNum];
int i,m,n;
对于(i=0;i>tempNum;
跟踪器++;
}
否则如果(跟踪器%2==0){
字符串流转换(num);
int tempNum2;
转换>>tempNum2;
myGraph.A[tempNum][tempNum2]=true;
跟踪器++;
}
}
}//结束
cout以下是一些观察结果:
tempNum
在if(tracker==0)
分支中使用之前未初始化。因此未定义2d数组分配大小
- 另外,
if(跟踪器%2==1)
分支中的声明int tempNum
会在while(graph.good())
循环开始之前对早期声明进行阴影处理。在分支结束时,此声明不再有效,因此获得的值不会在if(跟踪器%2==0))
分支中使用
在此块中创建一个新的本地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;