我已经阅读了很多有关此主题的文档,但是我仍然对此有一些疑问,我知道指针是什么,但是当我尝试使用ı时遇到了一些问题,在下面的代码中,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,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);
}