Miguel
Miguel

Reputation: 87

Structure not storing values and scanf failing

I'm trying to run the following code with some input, and when the program ends it shows that scanf failed and my structure didn't save anything except zeros. What's wrong?

Code:

#include <stdio.h>
#include <stdlib.h>

#define INF 2147483647;

typedef struct info{
    int u, v, w;
    struct info *next;
}*Vertex;

Vertex vertex;
int n, c, sede; 
int *distarr;

int main(){
    int i;

    if(scanf("%d %d\n%d", &n, &c, &sede) < 0)
        printf("first scanf failed\n");

    distarr = malloc(sizeof(int) * (n + 1));
    vertex = malloc(sizeof(struct info));

    for(i=0; i<c; i++){

        if(scanf("%d %d %d", &vertex->u, &vertex->v, &vertex->w) < 0)
            printf("second scanf failed\n");

        vertex->next = malloc(sizeof(struct info));
        vertex = vertex->next;

        printf("u: %d v: %d w: %d\n", vertex->u, vertex->v, vertex->w);
    }

    return 0;
}

Input:

10 15
6
6 2 5
6 7 -1
8 5 0
8 3 2
5 10 0
10 3 0
3 4 4
3 8 -1
2 5 4
2 10 5
2 3 1
2 9 3
1 6 -1
1 8 0
1 10 3

Output:

u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0
u: 0 v: 0 w: 0

EDIT: I saw that my condition of scanf was wrong I've changed it, but i still don't understand what is happening to just store 0 (The Code and Output were edited)

Upvotes: 2

Views: 200

Answers (2)

chux
chux

Reputation: 153508

Mis-ordered code: Print then advance pointer with vertex = vertex->next;.

    // Add
    printf("u: %d v: %d w: %d\n", vertex->u, vertex->v, vertex->w);

    vertex->next = malloc(sizeof(struct info));
    vertex = vertex->next;
    // printf("u: %d v: %d w: %d\n", vertex->u, vertex->v, vertex->w);

Upvotes: 1

haccks
haccks

Reputation: 106012

scanf("%d %d\n%d", &n, &c, &sede) will return 3 on successful scan and of course 3 != 1. Same goes with scanf("%d %d %d", &vertex->u, &vertex->v, &vertex->w).

Upvotes: 0

Related Questions