我对c语言有很多困难。 我正在尝试根据这个问题从txt文件生成图表: 为什么我在下面的代码中出现分段错误?
根据我的最佳答案进行更改后,generate_nodes方法正在运行。 但是现在我在generate_edges方法中遇到了问题。
图节点类型:
#ifndef Graph_Structure #define Graph_Structure #include 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: %sn", 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: %ldn", 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: %dn", (*graph)->id); while(temp2 != NULL){ if(temp2->id == dst){ //search for edge destination //printf("AQUI 2: %dn", 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; } } }
发生的事情是,当我尝试打印图形时,我陷入了方法print_graph中“while”内部的无限循环,这是没有意义的,因为我用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; }
以上就是c/c++开发分享为什么我的c代码从txt文件生成图表不起作用?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/522240.html