You had the right idea in your original code, passing the number of words to malloc(). Except you used the uninitialized variable n instead of the variable pos, which you incremented to count the number of words in the file.
But stop for a moment and think about what you're allocating. If you were to code this program with a limit on the number of words in a file, say WORD_COUNT, as well as a limit on the length of each word, say WORD_LENGTH, then your declaration might look something like this:
Code:
char word[WORD_COUNT][WORD_LENGTH];
You'd read words into that array as follows:
Code:
while(fscanf(pf,"%s",str) == 1)
{
strcpy(word[pos++], str);
}
Now, what if you were to dynamically allocate memory for word[][] instead of using fixed limits? First let's get rid of the WORD_COUNT limit, because it seems more restrictive. You end up with a declaration like this:
Code:
char *(word[WORD_LENGTH]);
Now, assuming that you know the number of words in the file, you can allocate memory for that array with
Code:
word = malloc(sizeof(*word) * words);
Then you'd read the file in the same way as you did for the word[WORD_COUNT][WORD_LENGTH] array.
Side note: malloc()
The common idiom for malloc() is
Code:
p = malloc(sizeof(*p));
or
Code:
p = malloc(sizeof *p);
because it works no matter what type p is (as long as p is a non-void pointer).
The parentheses for sizeof() can be left out if you're taking the sizeof() a variable rather than a type such as int.
In this case, sizeof(*word) is equivalent to sizeof(char []) or sizeof(char *).
You could also eliminate WORD_LENGTH instead:
Code:
char *word[WORD_COUNT];
or
Code:
char *(word[WORD_COUNT]);
You wouldn't need to allocate memory before you read from the file, but your file reading loop would have to look something like
Code:
while(fscanf(pf,"%s",str) == 1)
{
word[pos] = malloc(strlen(str) + 1); /* +1 for NULL */
strcpy(word[pos], str);
pos ++;
}
And then you'd need to free() the memory once you were done with it, of course.
But can we eliminate both restrictions on the dimensions? Will a declaration like this work?
Yes, of course it will. But you'll need to call malloc() in two places, to allocate memory for the array of pointers, which will contain the same number of elements as the file contains words; and you'll also need to allocate memory for each word.
I won't post the code for this final version; you ought to be able to figure it out yourself from my previous examples. If you can't, just say so.
Finally, what about realloc()? All of the above assumes that you know how many words are in the file, which you do not. I don't feel like posting a realloc() example, but you can search around for one. Here's a really old thread of mine that demonstrates this sort of thing:
http://cboard.cprogramming.com/showt...hlight=realloc