Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

c - Input variables use random values instead of the ones I want them to use

The inputs V, A and e inside the main function take on random values. Instead, I wanted to give them values through the inputs. I assume that it's because of the variables not being initialized in the graph function but these values come from structures. What did I do wrong?

Full code:

struct Edge {
    int src, dest, weight;
};

struct Graph {
    int V;
    int E;
    struct Edge* edge;
};

struct Graph* createGraph(int V, int E)
{
    struct Graph* graph = malloc(sizeof *graph);
    graph->V = V;
    graph->E = E;
    graph->edge = (struct Edge*)malloc(E * sizeof(struct Edge));
    return graph;
};

...

int main()
{
    int V = 0;
    int A = 0;
    int e = 0;
    int E = 0;
    int cidade = 0;
    int aeroporto = 0;
    int cidade1 = 0;
    int cidade2 = 0;
    int custo = 0;

    printf("Caso haja aeroportos, o vertice 0 e o ceu onde todos os aeroportos se ligam.
");
    printf("Caso nao haja aeroportos, o vertice 0 e uma cidade.

");
    printf("Introduza o numero de cidades: 
");
    scanf("%d", &V);
    printf("Introduza o numero de aeroportos: 
");
    scanf("%d", &A);
    printf("Introduza o numero de estradas: 
");
    scanf("%d", &e);
    printf("
");

    E = A + e;

    struct Graph* graph = createGraph(V, E);

    for (int i = 0; i < A; i++) {
        printf("Introduza a cidade e o custo de construcao do aeroporto: 
");
        scanf("%d %d", &cidade, &aeroporto);

        graph->edge[i].src = cidade;
        graph->edge[i].dest = 0; // vértice "céu"
        graph->edge[i].weight = aeroporto;
    }

    for (int j = 0; j < e; j++) {
        printf("Introduza as cidades e o custo da estrada: 
");
        scanf("%d %d %d", &cidade1, &cidade2, &custo);

        graph->edge[j].src = cidade1;
        graph->edge[j].dest = cidade2;
        graph->edge[j].weight = custo;
    }

    KruskalMST(graph);

    return 0;
}

question from:https://stackoverflow.com/questions/65893947/input-variables-use-random-values-instead-of-the-ones-i-want-them-to-use

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...