When in my load function, I insert a node at the front of a linked list:
If I declare and initialize a pointer as the new 'head' node, my code compile but every word in the text is found to be misspelt (i.e. the dictionary is silently not loading correctly) - see else
branch below.
If I instead use hashtable[hash(word)]
directly and without trying to initialize a pointer, which to me is at face value the same but not DRY, everything works perfectly.
It took me hours to find this and I cannot understand why the two behave differently. Can you help me to understand what is happening here so that I do not simply progress without 'getting' what is happening under the bonnet?
bool load(const char *dictionary)
{
// [UNNECESSARY CODE OMITTED AND SIGNPOSTED AS COMMENTS]
// Open dictionary to read from
// Pointer to a buffer for a word
// Loop through the dictionary, loading words into 'word' using the new node at front approach
while (fscanf(file, "%s", word) != EOF)
{
// Allocate memory for each linked list node
node *new_node = calloc(1, sizeof(node));
// Error check as the node will not be created if the program runs out of memory
else
{
// 2. If the node succeeds, copy the 'word' into your node (syntax: dest, source)
strcpy(new_node->word, word);
// ---> PROBLEM: New_node should point to whatever was previous in list
node *head = hashtable[hash(word)];
new_node->next = head;
head = new_node;
// count the new word added
wordsLoaded++;
}
}
// Close dictionary
// Indicate success
}