Reputation: 15
For some reason when I copy words from a file to an array, the last element is replacing all the contents from the previous indexes; however, I tested that the array is working fine before going throught the 'file loop' by adding text to index 0 and 1. Please take a look:
FILE *file = fopen("words.txt", "r");
if (file == NULL){
printf("...\n");
return false;
}
char *words[172805];
//Array test
words[0] = "abc";
words[1] = "bcde";
printf("%s, %s\n", words[0], words[1]);
// Copy words in text document to 'words' array.
while (!feof(file)) {
if (fgets(arraywordindic, 15, file) != NULL) {
//Remove \n from word in arraywordindic
arraywordindic[strcspn(arraywordindic, "\n")] = '\0';
words[i] = arraywordindic;
printf("%s\n", words[i]);
i++;
if (i == 4) {break;}
}
}
for (i = 0; i < 4; i++) {
printf("%s, ", words[i]);
}
fclose(file);
The output of above code is:
abc bcde
A
AA
AAH
AAHED
AAHED, AAHED, AAHED, AAHED,
Do you happen to know why this is happening? Thank you.
Upvotes: 0
Views: 55
Reputation: 211690
It looks like you're setting pointers to exactly the same buffer over and over. You need to copy the strings, or in other words:
words[i] = strdup(arraywordindic);
In C when you say char* x = y
this does not copy the contents of that string, it copies the pointer to the string.
Upvotes: 2