0

我正在尝试创建一个 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++;
    }
}
4

1 回答 1

0

除了内存泄漏

new_node = malloc(sizeof (vertex)); edge* new = malloc(sizeof (edge)); edge* new1 = malloc(sizeof (edge));

您的打印功能永远无法正常工作。head++永远不会变成NULL。

于 2016-03-09T07:42:37.670 回答