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

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error C – Array is not working when copying files from text file on this date .

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, %sn", 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")] = '';
        words[i] = arraywordindic;
        printf("%sn", 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.

Answer

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.