【发布时间】:2020-07-26 12:17:09
【问题描述】:
我已经阅读了很多关于这个主题的文档,但我仍然有一些问题,我知道指针是什么,但是当我尝试使用时我遇到了一些问题,在下面的代码中,txt 文件每个只包含一个单词行。我尝试从文本中读取随机行并返回到主函数,因为我需要这个)。我在主函数中打印它,请你帮我在这段代码中更改哪个部分?(当我尝试运行此错误消息是分段错误(核心转储))
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char word(char *file, char str[], int i);
int main() {
char buf[512];
char j = word("words.txt", buf, 512);
puts(j); // print random num
}
char word(char *file, char str[], int i) {
int end, loop, line;
FILE *fd = fopen(file, "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
srand(time(NULL));
line = rand() % 100 + 1; // take random num
for (end = loop = 0; loop < line; ++loop) {
if (0 == fgets(str, sizeof(str), fd)) { // assign text within a random line to STR
end = 1;
break;
}
}
if (!end)
return (char*)str; // return the str pointer
fclose(fd);
}
【问题讨论】:
-
char str作为函数参数是可疑的,sizeof(str) -
另外你为什么要打开文件两次?
-
你说得对,我没有必要编辑,但我仍然不明白这段代码有什么问题,我不明白为什么 char str 作为参数是可疑的?
-
因为它不包含字符串(一个单词),而只包含一个字符,例如 `a' 或 '\n'。
-
fgets需要一个字符 *,所以是一个地址。相反,您传递的是一个字符。尝试写入不是真实地址 = 段错误的地址。
标签: c arrays pointers random return-type