0

I am trying to read something from a txt file using fscanf. I am only reading a word in each time. And I am counting how many words I've collected. So that I can create a dynamic array with the count of words. Each element of array will contain a word. But I don't know how. Here is my code

pFile = fopen(inFile, "r");
char *chr;
if(pFile != NULL) // Process if the file is not empty
{
    while(!feof(pFile))
    {
        chr = (char*)malloc(sizeof(char*));
        num++;
        fscanf(pFile, "%s", chr);
    }
    printf("%s",chr);

}

And my example of the txt file is like that: hello world

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
phoeNix
  • 63
  • 1
  • 8

1 Answers1

1

sizeof is a compile time operator (with the exception of variable length array). In particular, sizeof(char*) is the size of a pointer to char, which is normally 4 in 32-bit machines, or 8 in 64-bit machines. So the size is not as dynamic as you thought.

An alternative is to malloc a small array first, use fgets to get the line, if the size is too small (you can check if a \n is got), realloc to a bigger size. Use sscanf to get the data from the line.

Also, you never free the memory dynamically allocated, so there's memory leak.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • Thank you I used free afterwards I know but im not about that one. I want to create an array withthe amount of read words.. – phoeNix Dec 30 '14 at 10:15