简体   繁体   中英

C - Array is not working when copying files from text file

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM