I'm trying to read from a file which has words in which are separated by spaces, the words are read within a loop. They are read correctly within the loop and they can be printed as so but as soon as the loop ends I am only able to print the first character of each element. Here is the code:
char **storeWords(char **words){
char* fileName = "words.txt";
FILE* fp = fopen(fileName, "r");
int i;
for (i = 0; i < 2; i++){
int j;
for (j = 0; j < 20; j++){
fscanf(fp, "%s", &words[i][j]);
printf("%s", &words[i][j]); //prints correctly
}
}
printf("%s", &words[0][0]); //prints first character of selected element
fclose(fp);
return **words;
}
int main(){
char **words = (char**)malloc(6 * sizeof(char*));
for (int i = 0; i < 6; i++){
words[i] = (char*)malloc(20 * sizeof(char));
}
storeWords(words);
system("pause");
return 0;
}
I don't understand why this happens, it would be appreciated if this could be explained. Thanks.
fscanf(fp, "%s", &words[i][j]);overwrited each one shift.for (i = 0; i < 2; i++){ fscanf(fp, "%19s", words[i]); printf("%s\n", words[i]); }return **words;should bereturn words;. Doesn't your compiler complain on this line?