phoeNix
phoeNix

Reputation: 63

fscanf and dynamic array allocation

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

Upvotes: 0

Views: 1451

Answers (1)

Yu Hao
Yu Hao

Reputation: 122433

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.

Upvotes: 1

Related Questions