0
#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.

Edited by gyuunyuu: n/a

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by kings_mitra
0

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

Edited by gyuunyuu: n/a

0

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 :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.