我在使用c语言方面遇到很多困难。我目前正在尝试根据此问题从txt文件生成图表:why am I getting segmentation fault on the code below?
根据我的最佳答案进行更改后,generate_nodes方法正在运行。但现在我在generate_edges方法中遇到了问题。
图节点类型:
#ifndef Graph_Structure
#define Graph_Structure
#include <stdbool.h>
struct Graph_Node{
int id;
char node_name[100];
bool path;
struct Graph_Node* next;
struct Graph_Node* edge;
struct Graph_Node* next_edge;
};
typedef struct Graph_Node graph_node;
#endif
generate_edges方法:
int generate_edges(graph_node **graph, const char *file_name){
FILE *fp = fopen(file_name, "r");
if(fp == NULL)
{
fprintf(stderr, "Error opening file %s: %s\n", file_name,
strerror(errno));
return 0;
}
char line[1024];
size_t linenmr = 0;
while(fgets(line, sizeof line, fp))
{
linenmr++;
// getting rid of the newline
line[strcspn(line, "\n")] = 0;
if(strlen(line) > 12)
continue; // resume reading, skip the line
char *sep;
long int dst = strtol(line, &sep, 0);
sep++;
long int src = strtol(sep, &sep, 0);
//search for edge in graph
//printf("dst: %ld ", dst); printf("src: %ld\n", src);
add_edge(graph, src, dst);
}
return 1;
}
add_edge方法:
void add_edge(graph_node **graph, int src, int dst){
graph_node* temp = *graph;
graph_node* temp2 = *graph;
while(*graph != NULL){
if((*graph)->id == src){ //search for edge source
//printf("AQUI: %d\n", (*graph)->id);
while(temp2 != NULL){
if(temp2->id == dst){ //search for edge destination
//printf("AQUI 2: %d\n", temp->id);
(*graph)->next_edge = (*graph)->edge;
(*graph)->edge = temp2;
break;
}
temp2 = temp2->next;
}
temp2 = temp;
break;
}
*graph = (*graph)->next;
}
*graph = temp;
}
print_graph方法:
void print_graph(graph_node* graph){
if(graph == NULL){
return;
}
else{
graph->path = true;
printf("%d ", graph->id);
puts(graph->node_name);
printf("\n");
while(graph->edge != NULL){
if(graph->edge->path == false)
print_graph(graph->edge);
graph->edge = graph->next_edge;
}
}
}
正在发生的事情是,当我尝试打印图形时,我陷入无限循环内部&#34;而#34;从方法print_graph开始,因为我用null初始化所有节点的边缘,所以没有意义。它就像一个节点没有带空值的边缘,但这里是我更新的插入代码:
void insert_node(graph_node** node, graph_node data){
graph_node* temp = (graph_node*)malloc(sizeof(graph_node));
temp->id = data.id;
strcpy(temp->node_name, data.node_name);
temp->node_name[sizeof(temp->node_name) - 1] = 0;
temp -> edge = NULL;
temp -> next_edge = NULL;
temp -> path = false;
temp -> next = *node;
*node = temp;
}