I have a question regarding the use of malloc and realloc:
for this, "part", of my assignment, I have to read in every word from a text file and count the number of times it appears in a text file. The definition of a word in this assignment is very simplistic in such that a word is defined as having a space between them, so any punctuation attached to a word is part of the word.
The gotcha is I have to use a dynamically allocated array to store the words using realloc and malloc.
Heres some of the code I was giving to demonstrate this using some test words
char **wordlist = malloc(sizeof(char*)):
int i, numwords = 0;
char*testwords[] = { "hello", "there", "folks", "in", "1840"};
wordlist[0] = strdup(testwords[0]);
for(i =1; i sizeof(testwords) / sizeof(testwords[0]); i++)
{
wordlist =realloc(wordlist,(numwords +1) * sizeof(char*));
wordlist[numwords] = strdup(testwords[i]);
numwords++;
}
printf("Added %d words to the array and they are:\n", numwords);
for (i = 0; i < numwords ; i++)
printf(%s\n", wordlist[i]);
return(0);
}
Now right now I'm just trying to read in the words from file and put them into a dynamically allocated array, not caring about the order.
My main question is what method should I use to read in the data, fgets and fscanf come to mind. Also, how to I declare the array which takes place of testwords in the above example. For testwords, the size is allocated when i define it, but when i read in from a file i don't know how big I should make it so i end up with segmentation faults.
I am no programming expert and my book doesn't really go into detail about realloc, and it barely touches malloc. Any insight would be greatly appreciated.