0

For some reason, the position returning in this line of code always returns as 0, which clearly doesn't work. I believe it has something to do with how the words from the dictionary are loaded in.

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

    for(int i = 0; i < 26; i++)
    {
        hashtable[i] = NULL;
    }

    // Insert words into hash table
    //fscanf already reads the information and puts it into file
    while (!feof(file))
    {
        fscanf(file, "%s", new_node->word);
        //allocate memory of a node
        new_node = malloc(sizeof(node));
        if(new_node == NULL)
        {
            return false;
        }
        const char*string = new_node->word;
        new_node->next = NULL;

        //find the position where the word should be in the hash table
        int position = hash(string[0]);
        //put the original information into a temp position
        node*first = hashtable[position];

        //put the new information into the original position
        if(first == NULL) //if there was no information
        {
            hashtable[position] = new_node; //create a node
        }
        else
        {
            new_node->next = hashtable[position]; //move information to the next position
            hashtable[position] = new_node; //move new information to the original position
        }
        counter++;
    }
    // Close dictionary
    fclose(file);
    // Indicate success
    return true;
}
0

Not sure why you hashtable[i] = NULL; in two different loops.

Where do you declare new_node? No need to make that global.

feof does not work exactly like you want it to (you will have last word twice if you do it that way). You could fix that by doing like while (fscanf(...) != EOF) without any feof.

Either fscanf to word and later strcpy to new_node->word, or allocate a node in advance, allocate new nodes only at the end of the loop, and free the unused extra node after the loop.

I totally not get const char*string = new_node->word;. There is no point in giving the string another name.

1
  • It works after all your edits! THank you so much Jan 22 '19 at 15:36

You must log in to answer this question.

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