I have a program that counts word occurrences in a text file and stores them in an array. So far I'm using a fixed array and everything works fine but now I'd like to change that to a dynamic array so there is never any memory wasted/required. I understand that malloc and realloc must be used to accomplish this but I don't really understand how to go about doing it.
My first idea was to simply count the words in the text file then malloc enough space for all of them but this will leave wasted space as duplicate words will have a counter increased, but not be added to the array again.
Does this approach sound like it makes sense and would be the best way to go about accomplishing it? If I first malloc a small array just enough to find one word and its counter. Then each time I find a new word that needs adding to the array just realloc enough to fit another word and counter in. If it's a duplicate no realloc will be needed as an existing counter will just be incremented.