The program below describes: read everything in library.txt then put it in a level 2 char pointer, choose ramdomly a word from the pointer then use strlen to print a number of characters in that word. The problem is every number of characters are increase by 2 units. Examples:
helloworld (10 letters) -> 12 letters
abcdef (6 letters) -> 8 letters
uiop (4 letters) -> 6 letters
SUB-QUESTION: can anyone show me the way to return a char pointer from a function? I tried to do like this " char *read (FILE *library) " but on the Internet, they told me not to do that, so i did like the function below =)). please help.
#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;
}