结构不存储值和 scanf 失败
Structure not storing values and scanf failing
我正在尝试 运行 下面的代码和一些输入,当程序结束时它显示 scanf
失败并且我的结构除了零之外没有保存任何东西。怎么了?
代码:
#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;
}
输入:
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
输出:
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
编辑:我看到我的 scanf 条件是错误的,我已经更改了它,但我仍然不明白只存储 0 发生了什么(代码和输出已编辑)
scanf("%d %d\n%d", &n, &c, &sede)
将 return 3
扫描成功,当然还有 3 != 1
。 scanf("%d %d %d", &vertex->u, &vertex->v, &vertex->w)
.
也是如此
顺序错误的代码:打印然后 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);
我正在尝试 运行 下面的代码和一些输入,当程序结束时它显示 scanf
失败并且我的结构除了零之外没有保存任何东西。怎么了?
代码:
#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;
}
输入:
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
输出:
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
编辑:我看到我的 scanf 条件是错误的,我已经更改了它,但我仍然不明白只存储 0 发生了什么(代码和输出已编辑)
scanf("%d %d\n%d", &n, &c, &sede)
将 return 3
扫描成功,当然还有 3 != 1
。 scanf("%d %d %d", &vertex->u, &vertex->v, &vertex->w)
.
顺序错误的代码:打印然后 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);