【发布时间】:2021-12-28 07:23:24
【问题描述】:
我是 C 新手。在在线 C 编译器中运行以下图形遍历算法程序时出现分段错误。我知道错误是由于访问了尚未初始化或无法访问的内存,但我不知道错误发生在哪里。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define max 5
struct vertex{
char name;
bool isVisited;
};
int queue[max];
int rear = -1, front = 0, queueCount = 0, vertexCount = 0;
struct vertex* adjList[max];
int adjMat[max][max];
void insert(int data){
queue[++rear] = data;
queueCount++;
}
int delete(){
queueCount--;
return queue[front++];
}
bool isEmpty(){
return queueCount == 0;
}
void addVertex(char name){
struct vertex* v = (struct vertex*)malloc(sizeof(struct vertex));
v->name = name;
v->isVisited = false;
adjList[vertexCount++] = v;
}
void addEdge(int start, int end){
adjMat[end][start] = 1;
adjMat[start][end] = 1;
}
void display(int vertexIndex){
printf("%c", adjList[vertexIndex]->name);
}
int getAdjUnvisitedVertices(int vertexIndex){
for (int i = 0; i < vertexCount; i++){
if (adjMat[vertexIndex][i] == 1 && adjList[i]->isVisited == false){
return i;
}
}
return -1;
}
void BFS(){
adjList[0]->isVisited = true;
display(0);
insert(0);
int unvisitedVertex;
while (!isEmpty()){
int tempVertex = delete();
while (unvisitedVertex = getAdjUnvisitedVertices(tempVertex) != -1){
adjList[unvisitedVertex]->isVisited = true;
display(unvisitedVertex);
insert(unvisitedVertex);
}
}
for (int i = 0; i < vertexCount; i++){
adjList[i]->isVisited = false;
}
}
void main(){
for (int i = 0; i < max; i++){
for (int j = 0; j < max; j++){
adjMat[i][j] = 0;
}
}
addVertex('S');
addVertex('A');
addVertex('B');
addVertex('C');
addVertex('D');
addEdge(0,1);
addEdge(0,2);
addEdge(0,3);
addEdge(1,4);
addEdge(2,4);
addEdge(3,4);
printf("Breadth First Traversal : ");
BFS();
}
【问题讨论】:
-
使用调试器查找错误发生的位置。
-
@kiner_shah 我不知道如何使用调试器,因为我是 C 新手
-
哪个 IDE?哪个操作系统?
-
我尝试了许多编译器,如 OnlineGDB、tutorialspoint IDE、OneCompiler 和 programiz。全部显示分段错误或 SIGSEGV 错误和监控的命令转储核心错误
-
在线 GDB 上有一个调试代码的选项。但是,是的,我认为您可能会面临学习如何使用它的困难(它是 GDB)。
标签: c memory graph segmentation-fault runtime-error