0

I have been stuck on pset4 for quite some time without any meaningful progress. After re-watching the walkthroughs and reading answers here I've sort of put together a "frankenstein" thing for the load function:

// hash function
int hash(const char *word)
{
  int hash_key = toLower(word[0] - 'a') % 26;
  return hash_key;
}

int index = hash(new_node->word);

bool load(const char *dictionary)
{
// Initialize hash table
for (int i = 0; i < N; i++)
{
    hashtable[i] = NULL;
}

// Open dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
    unload();
    return false;
}

// Buffer for a word
char word[LENGTH + 1];

// Insert words into hash table
// take a dictionary file, look for a string (%s), then put that string in a variable - word
// loop runs until the end of the file (dictionary) is reached
while (fscanf(file, "%s", word) != EOF)
{
    // make new node and allocate space for it
    node *new_node = malloc(sizeof(node));

    // malloc returns NULL when you run out of memory
    if (new_node == NULL)
    {
        unload();

        // speller will quit when false is returned
        return false;
    }
     // copy a word into the node
     strcpy(new_node->word, word)

     new_node->next = hashtable[index];
     hashtable[index] = new_node;

     word_count ++;
}


// Close dictionary
fclose(file);

// Indicate success
return true;
}

Can anyone point me in the right direction on what I supposed to do next or what is wrong with the current snippet?

0
  1. You cannot define a function inside another function. Define it above, or declare it above and define it below, whatever you want.
  2. toLower(word[0] - 'a') probably was meant to be tolower(word[0]) - 'a'
  3. The whole head thing makes no sense to me. Shouldn't you use hashtable[index] (after hashing!) for that?
2
  • I have edited the snippet based on your suggestion. With your second point should it become (toLower(word[0]) - 'a') % 26? – alljamin Mar 17 '20 at 10:33
  • @alljamin tolower(a[i]) - 'a' or tolower(a[i]) - 65 will never be greater than 26, provided a[i] is an alphabet. – C-- Apr 12 at 14:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .