Put data from file to array in C

here is my code.

#include <stdlib.h> #include <stdio.h> int main() { //Vars FILE *fp; char word[9999], *arrayOfWords[9999]; int wordCount = 0, i; //Actions fp = fopen("data.txt", "r"); if(fp != NULL) { while(!feof(fp)) { fscanf(fp, "%s", word); arrayOfWords[wordCount] = word; wordCount++; } for(i = 0; i < wordCount; i++) { printf("%s \n", arrayOfWords[i]); } puts(""); } else { puts("Cannot read the file!"); } return 0; } 

I am trying to read some data from a text file and store it in an array. Everything is fine as long as I am in the loop, but when I exit from there, any value of any index in my array is filled with the last word of the file. Can someone help me find out the mistakes that I make?

Data file:

 Hello there, this is a new file. 

Result:

 file. file. file. file. file. file. file. file. 

Any help would be appreciated!

+4
source share
3 answers

There are at least 2 problems in your code. char word[9999], *arrayOfWords[9999]; defines arrayOfWords as an array of 9999 char pointers . This is one of the problems.

Another point is arrayOfWords[wordCount] = word; . Here, to save the newly read word, you need to allocate space, since arrayOfWords is an array of pointers. Please find the modified code as shown below.

 int main() { //Vars FILE *fp; char arrayOfWords[30]; int wordCount = 0, i; //Actions fp = fopen("data.txt", "r"); if(fp != NULL) { while(!feof(fp)) { fscanf(fp, "%s", &arrayOfWords[wordCount]); wordCount++; } puts(""); for(i = 0; i < (wordCount - 1); i++) { puts(arrayOfWords[i]); } puts(""); } else { puts("Cannot read the file!"); } return 0; } 
+1
source

You need to allocate memory for each individual member of your array (using malloc or by providing a second dimension to the array and declaring its type char instead of char* ). What you do is like:

 char *s; scanf("%s", s); 

And this cannot work in C In fact, here you have UB (undefined) behavior, because the pointer is not initialized.

EDIT: you will get all the fields in the array to instead indicate your word array, after you read the word, you must allocate new memory for the string, and then strcpy word .

+2
source

It:

 arrayOfWords[wordCount] = word; 

It does not copy the current word to a separate storage, it simply assigns to another pointer an indication of the same piece of memory as word . Thus, you get an array of pointers to the same word array. You need to separately allocate memory for each word and copy the characters that make up each word (and the NULL terminator), not the pointer.

0
source

All Articles