下面的程序描述:读取 library.txt 中的所有内容,然后将其放入 2 级 char 指针中,从指针中随机选择一个单词,然后使用 strlen 打印该单词中的多个字符。问题是每个字符数增加 2 个单位。例子:
helloworld(10 个字母)-> 12 个字母
abcdef (6 个字母) -> 8 个字母
uiop(4 个字母)-> 6 个字母
子问题:谁能告诉我从函数返回 char 指针的方法?我试图这样做“char *read (FILE *library)”,但在互联网上,他们告诉我不要这样做,所以我确实喜欢下面的函数 =))。请帮忙。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read (FILE *library){
// count number of word in library.txt
int n=0;
char *s=(char *)malloc(256*sizeof(char));
library=fopen("C:\\Users\\pc\\Desktop\\library.txt","rb");
while (fgets(s, 256, library)!=NULL)
{
n++;
}
free(s);
rewind(library);
// put all words in library.txt to the level 2 pointer
char **word=(char**)malloc(n*sizeof(char *));
for (int i = 0; i < n; i++)
{
*(word+i)=(char *)malloc(256*sizeof(char));
fgets(*(word+i), 256, library);
}
fclose(library);
// choose a rondom word then return it to function
int j=0;
srand((int) time(0));
j=rand()%n;
return (int)*(word+j);
}
int main(){
FILE *library;
int length_word=0;
length_word=strlen(read(library));
printf("%s%d",read(library),length_word);
return 0;
}