
我是个 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 pursuer 2020 年 10 月 11 日 via Android 看起来没有给 name 分配内存,像 char *name=(char *)malloc(50)或者 char name[50]这样? |
2 BrettD 2020 年 10 月 11 日 via iPhone name 是野指针啊! |