0

I'm trying to write a program that reads multiple files and stores all the words in one array of strings. Here are some parts of the code:

This is the array that I'm supposed to put the words in:

I also dynamically allocate memory to this array and free it, so the issue is not that. For some reason, after the while loop, when I try to print out the array, it is empty, like nothing was written to it.

If you need any other parts of the code, let me know, I'll gladly post it.

michael368
  • 43
  • 3

1 Answers1

0

Assuming that word_collection.all_words is valid for all indexes you're using, then the assignment

word_collection.all_words[wc_pos++] = word;

will make all elements of word_collection.all_words point to the exact same location: The first element of the single word array.

This is one problem, there's also another possible problem with this: If word is not a global variable, then as soon as the function that defines word returns, the life-time of word will end, making all those pointers invalid.

To solve both those problems you need to allocate memory for each element as well, and copy the string from word. This can be done by the commonly available strdup function:

word_collection.all_words[wc_pos++] = strdup(word);

Of course you have to remember to free all the pointers returned by strdup.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • That char word is basically a scanned word that I'm recycling every time I scan a new word from file, that's the only use. To allocate the memory I did this: word_collection.all_words = malloc(100 * sizeof(char*)); Is that enough or do I have to malloc each string specifically? – michael368 May 24 '20 at 15:12
  • Also I to free, I do free(word_collection.all_words) which I think should do the job, right? – michael368 May 24 '20 at 15:21