我正在尝试创建一个C程序,该程序读入一个输入文件,该文件包含一组表示无向图边缘的点。我试图将每个顶点结构存储在使用指针实现的数组中,但是在load_file运行后数组不会保存所有顶点,它只包含第一个顶点。我也不确定如何实现DFS来查找每个顶点和顶点之间的边数1.目前底部函数是这个逻辑发生的地方,但我不知道该怎么做。
#include <stdio.h>
#include <stdlib.h>
#include "../HW3/input_error.h"
#define VertexToSearch 1
typedef struct node {
int value;
struct node* nextedge;
}edge;
typedef struct node1 {
int vertexnumber;
int distance;
edge* edge;
} vertex;
vertex* load_file(char*, vertex*);
vertex* create_vertex_list(vertex*, int*);
vertex* create_new_edge(int*, int*, vertex*);
void print_distance(vertex*);
vertex* find_vertex(vertex*,int);
enum error program_error;
int main(int argc, char** argv) {
vertex* array;
array = load_file(argv[1], array);
print_distance(array);
}
vertex* load_file(char* filename, vertex* head) {
int* count = malloc(sizeof (int));
int* vertex1 = malloc(sizeof (int));
int* vertex2 = malloc(sizeof (int));
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("%s did not open", filename);
program_error = FILE_FAILED_TO_OPEN;
exit(program_error);
}
fscanf(file, "%d", count);
head = malloc(sizeof(vertex)* *count);
head = create_vertex_list(head, count);
for (int i = 0; i<*count; i++) {
fscanf(file, "\n(%d,%d)", vertex1, vertex2);
head = create_new_edge(vertex1, vertex2, head);
}
free(count);
free(vertex1);
free(vertex2);
fclose(file);
return head;
}
vertex* create_vertex_list(vertex* head, int* count) {
vertex *new_node, *current;
for (int i = 0; i<*count; i++) {
new_node = malloc(sizeof (vertex));
new_node->vertexnumber = i + 1;
new_node->edge = NULL;
new_node->distance = 0;
head[i] = *new_node;
}
return head;
}
vertex* create_new_edge(int* vertex1, int* vertex2, vertex* head) {
edge* new = malloc(sizeof (edge));
edge* new1 = malloc(sizeof (edge));
new->value = *vertex1;
new1->value = *vertex2;
new->nextedge = NULL;
new->nextedge = NULL;
head[*vertex1].edge = new1;
head[*vertex2].edge = new;
return head;
}
void print_distance(vertex* head){
while(head != NULL){
if(head->edge->value == VertexToSearch){
printf("found");
}
head++;
}
while(head != NULL){
printf("%d %d\n",head->vertexnumber,head->distance);
head++;
}
}
答案 0 :(得分:0)
除了内存泄漏
new_node = malloc(sizeof (vertex));
edge* new = malloc(sizeof (edge));
edge* new1 = malloc(sizeof (edge));
您的打印功能永远不会有效。 head++
永远不会变为NULL。