请问这段 fscanf 的代码为什么没有达到预期的效果?

2020-10-11 08:21:17 +08:00
 abucus

我是个 C 语言初学者,查了很多网上的资料(包括 API 文档)还是没有头绪,请了解的大佬帮忙看看。题目是用 c 代码读取一个 txt 文件,这个 txt 文件里存储了图的信息,包括节点和边,内容如下

3
a
b
c
a b
a c
b c

第一行的数字表示这个图有多少节点。我最初始的版本读取边信息用了 while 循环

#include<stdio.h>

int main(int argc, char *argv[])
{

    int n;

    FILE *file = fopen(argv[1], "r");

    fscanf(file, "%d", &n);

    // read node
    char *name;
    for(int i = 0; i < n; i++)
    {
        fscanf(file, "%s", name);
        printf("read node %s\n", name);
    }

    //read edge
    char *name1;
    char *name2;

    while(fscanf(file, "%s %s", name1, name2) != EOF)
    {
        printf("read edge %s %s\n", name1, name2);
    }
}

编译无错误,执行的时候发现这个 while 循环不结束,而且输出的数据也很奇怪,如下

read node a
read node b
read node c
read edge (null) ??1?I??^H??H???PTL?F
read edge (null) ??1?I??^H??H???PTL?F
read edge (null) ??1?I??^H??H???PTL?F
read edge (null) ??1?I??^H??H???PTL?F
read edge (null) ??1?I??^H??H???PTL?F
...

请问这是为什么呢?

PS 我尝试只保留 while 读取,并且在 txt 文件里只保存边信息,发现读取结果是下面这样

read edge a (null)
read edge b (null)
read edge a (null)
read edge c (null)
read edge b (null)
read edge c (null)

从这里看好像是 fscanf 好像不支持 “%s %s”这样的 format,于是我又有了新问题:

  1. 为什么同样是 while 循环读取,这里和上面的结果这么不一样?
  2. 要怎么样改才能正常工作?
2108 次点击
所在节点    C
3 条回复
pursuer
2020-10-11 08:40:19 +08:00
看起来没有给 name 分配内存,像 char *name=(char *)malloc(50)或者 char name[50]这样?
BrettD
2020-10-11 09:10:33 +08:00
name 是野指针啊!
abucus
2020-10-11 09:27:33 +08:00
@pursuer @BrettD 还真是这个问题,改了以后就正常了,多谢大佬们

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/713846

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX