here's my code.
#include <stdlib.h>
#include <stdio.h>
int main() {
//Vars
FILE *fp;
char word[9999],
*arrayOfWords[9999];
int wordCount = 0, i;
//Actions
fp = fopen("data.txt", "r");
if(fp != NULL) {
while(!feof(fp)) {
fscanf(fp, "%s", word);
arrayOfWords[wordCount] = word;
wordCount++;
}
for(i = 0; i < wordCount; i++) {
printf("%s \n", arrayOfWords[i]);
}
puts("");
} else {
puts("Cannot read the file!");
}
return 0;
}
I am trying to read some data from a text file and store it into an array. Everything is fine while I'm in the loop, but when I get out of there, any value of any index in my array is filled with the last word of the file. Could anyone help me find out mistakes I am doing?
Data file:
Hello there, this is a new file.
Result:
file.
file.
file.
file.
file.
file.
file.
file.
Any help would be appreciated!
This:
does not copy the current word into separate storage, it merely assigns another pointer to point to the same piece of storage that
word
does. So you end up with an array of pointers to the sameword
array. You need to separately allocate memory for each word and copy the characters that make up each word (and the NULL terminator), rather than the pointer.There are atleast 2 points of concern in your code.
char word[9999], *arrayOfWords[9999];
definesarrayOfWords
to be an array of 9999char pointers
. This is one point of concern.Another point is
arrayOfWords[wordCount] = word;
. Here to store the newly read word, you need to allocate space asarrayOfWords
is an array of pointers. Please find your modified code as below.You need to allocate memory for each individual member of your array(using malloc or by giving a second dimension of the array and declaring it of type
char
instead ofchar*
). What you do is similar to:And this can not work in
C
. In fact here you have UB(undefined behavior), because the pointer is not initialized.EDIT: you get all the fields in the array to point to your array
word
instead, once you have read word you should allocate new memory for the string and thenstrcpy
word
into it.