0

I am trying to read a file containing a list of words and store them in an array. After storing I randomly tried to print the 10th element to ensure that the code did what it's supposed to but I was unsuccessful. I also get the following warning and I don't get what it's telling me:

warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion] 22 | dict[i][j]=word_scanned;

#include <stdio.h>

#include <stdlib.h>

int main() {

    char word_scanned[50];

    char dict[102402][50];

    int i,j;

    FILE *fptr;

    if ((fptr = fopen("/usr/share/dict/words", "r")) == NULL) {

        printf("Error! opening file\n");

        // Program exits if file pointer returns NULL.

        exit(1);

    }


   for(i=0; !feof(fptr); i++){

        fscanf(fptr,"%s", word_scanned);

       for (j=0; j<50; j++){

            dict[i][j]=word_scanned;  

       }

   }

    printf("%s\n",dict[9]);

    fclose(fptr);

    return 0;  
}
  • Note that the 5 megabytes of array might be too much for the stack. – Weather Vane Feb 18 '20 at 17:56
  • 1
    [Why while(!feof()) always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)? – KamilCuk Feb 18 '20 at 17:57
  • Is better to control that loop with `while(fscanf(fptr,"%49s", word_scanned) == 1)` – Weather Vane Feb 18 '20 at 17:59
  • `dict[i][j]=word_scanned;` is incorrect too. Should either be `word_scanned[j]`, or better to use `strncpy`. – Weather Vane Feb 18 '20 at 18:01
  • These seems like completely arbitrary numbers and they're probably wrong. Why not dynamically allocate as necessary? You can scan to count lines, allocate the right number of `char*` pointers, then read in each line and `strdup` it into the array. You'll never allocate incorrectly. – tadman Feb 18 '20 at 18:19

1 Answers1

0

dict[i][j]=word_scanned[j]; is the answer.

But also read about strncpy, and also FYI fscanf(fptr,"%s", word_scanned); is not safer than directly scanning into fscanf(fptr,"%s", dict[i]); because word_scanned is 50 bytes long, too. Any string longer than 50 characters will cause memory error, so this additional buffer does not help at all.

NickDoom
  • 339
  • 1
  • 9