【发布时间】:2018-12-02 12:47:25
【问题描述】:
我是编程新手,我尝试使用 c++ 编程语言使用邻接表来实现图形。
图表数据的上传似乎有效。但是当我尝试打印图表时遇到问题:Segmentation fault: 11。具体发生在顶点57。我认为程序的逻辑还可以,但我不知道错误在哪里。
文本文件:data.txt
以及源代码:
//
// main.cpp
// Dijkstra
//
// Created by Ibrahim El Mountasser on 02/12/2018.
// Copyright © 2018 Ibrahim El Mountasser. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
const int SIZE = 201;
struct Node{
int data;
int weight;
struct Node* next;
};
struct LinkedList {
struct Node* head;
};
class Graph {
public: LinkedList list[SIZE];
public:
Graph(std::string fileName) {
std::ifstream infile(fileName);
if(!infile.is_open()) return;
std::string line;
int i = 0;
while ( i < SIZE && getline(infile, line) )
{
std::istringstream str(line);
int u;
int w;
str >> u;
if ( u > SIZE )
{
// Problem.
std::cout<<"u is too large!"<<std::endl;
exit(-1);
}
int v;
char c;
while ( str >> v >> c >> w)
{
if( u < v)
{
createEdge(u, v, w);
std::cout<<"createEdge("<<u<<","<<v<<","<<w<<");"<<std::endl;
}
}
}
}
Node* createNode(int data, int weight){
Node* newNode = new Node;
newNode->data = data;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}
void createEdge(int src, int dist, int weight) {
Node* newNode = createNode(dist, weight);
newNode->next = list[src].head;
list[src].head = newNode;
newNode = createNode(src, weight);
newNode->next = list[dist].head;
list[dist].head = newNode;
}
void printGraph() {
for (int i=0; i<SIZE; i++) {
std::cout<<i;
Node* temp = list[i].head;
while (temp != NULL) {
std::cout<<" -> "<<temp->data<<","<<temp->weight; // <== segfault here
temp = temp->next;
}
std::cout<<std::endl;
}
}
};
int main() {
Graph gr("data.txt");
gr.printGraph(); // <========= segfault when calling this
return 0;
}
【问题讨论】:
-
您在逐行调试应用程序时发现了什么?异常发生在哪里?我认为这是由于未定义的初始值
-
使用矢量代替:
public: LinkedList list[SIZE];。使用适当的设计,甚至可能使用 boost::graph。 -
异常确实发生在这一行 std::cout "dataweight; [3,1239] 的下一个节点
-
struct LinkedList { struct Node* head = nullptr; };它应该可以解决您的问题。在 printGraph 中,list[0].head是不确定的,因为您的数据从 1 个索引开始。 -
这行得通! @rafix07
标签: c++ algorithm data-structures graph