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]);

printf("Added %d words to the array and they are:\n", numwords);
for (i = 0; i < numwords ; i++)
  printf(%s\n", wordlist[i]);

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.

I'm not sure if this is correct, so take this more as a suggestion from another novice than an actual answer.

If you're going to be taking the word list from arguments from the command line you can declare a an array of char* words[argc-1]; Since the first argument is the name of the program, it should only need the amount of arguments -1.

If you're reading from a file I think you'll only have to malloc enough space for the char*s themselves, since the words are already stored in memory elsewhere and won't need need any more memory allocated for them.

read the man page for fgets and fscanf, and maybe even malloc/realloc (if you're using emacs just m-x man, and then type the name of the function you want to read about). Lots of times in situations like these the man pages will direct you towards a solution just because you may see a related function you didn't know existed, or by just seeing usage examples.

Good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.