#include <stdio.h>
#include <string.h>

typedef struct {
    int count; // counter to use the word's occurrence
    char *word;
} word;

int main() {

    word myword[50];
    FILE *myfile;

    if ((myfile = fopen("wordlist", "r")) == NULL) {
        printf("\n Error:Can't open file \n ");
        exit(0);
    }

    char str[99];
    int position = 0;

    while (fscanf(myfile, "%s", str) != EOF) {
        myword[position].word = str;
        printf("myword[%d].word is: %s\n",position, myword[position].word);
        position++;
        if (position == 50) {
            break;
        }
    }
    printf("testing myword[0].word: %s\n", myword[0].word);
    printf("testing myword[25].word: %s\n", myword[25].word);
    printf("testing myword[49].word: %s\n", myword[49].word);
    return 0;
}

Why do the last 3 printf lines return the same word: 50th word(myword[49].word)? The printf inside the while loop shows myword[position].word like it's supposed to.

I found out every value get replaced with current found word. Am I doing something wrong with pointers?

Definitely, you are doing wrong with pointers.

Your statement

myword[position].word = str;

will make all the pointers to point to the same variable, which ultimately holds the last read word after the end of the loop.
So, dereferncing any of the pointers (after the loop) will result in displaying the same value that "str" contains (that is the last read word).

You need to change the variable str from char * to char array and do a strcpy in place of the above statement to populate the str member with respective words from the file.

Cheers :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.