0

can someone have look at my PSET5 - speller code. I have tried to fix it for five hours, and I don't seem to go anywhere. Thanks in advance!

typedef struct node{
    char word[LENGTH+1];
    struct node* next;
} node;

node *hashTable[HASH_TABLE_SIZE];
int wordCount =0;

/**
 * Returns true if word is in dictionary else false.
 */
bool check(const char *word)
{
    int hashNumber = (int) tolower(word[0]) - 96;
    node* cursor = hashTable[hashNumber];
    while(cursor!=NULL)
    {
        if(strcmp(cursor->word,word)==0) return true;
        cursor = cursor->next;
    }
    return false;
}

/**
 * Loads dictionary into memory. Returns true if successful else false.
 */
bool load(const char *dictionary)
{
    FILE *file = fopen(dictionary,"w");
    if (!file) return false;
    char word[LENGTH+1];
    while(fscanf(file, "%s\n", word) != EOF){
        cnt++;
        for(int i=0; i<LENGTH+1; i++ )
            if(word[i]=='\n') {
                word[i]='\0';
                break;
            }
        int hashNumber = (int) tolower(word[0]) - 96;
        node *cursor = malloc(sizeof(node));
        strcpy(cursor->word, word);
        cursor -> next = hashTable[hashNumber];
        hashTable[hashNumber] = cursor;
    }

    fclose(file);
    return true;
}

/**
 * Returns number of words in dictionary if loaded else 0 if not yet loaded.
 */
unsigned int size(void)
{
    return cnt;
}

/**
 * Unloads dictionary from memory. Returns true if successful else false.
 */
bool unload(void)
{
    int i=0;
    while(i<26)
    {
        node *cursor = hashTable[i];
        while(cursor != NULL)
        {
            node* temp = cursor;
            cursor = cursor->next;
            free(temp);
        }
    }
    return true;
}
3

Why is it that the simplest errors are the most frustrating and then others hide it?

You have two major issues to deal with, followed by a handful of minor ones. I'll point you at the majors and you can debug the rest.

First, the infinite loop is being caused by your unload function. If i is never changed, the loop will never end. A rethink of the code is in order.

Now the fun one. I'll wager that your dictionary file is empty after you execute this code. (Suggest you test with a small dictionary for now.)

Take a look at the following line:

        FILE *file = fopen(dictionary,"w");

What happens to the contents of a file when you open it for WRITE?

There are other minor issues to be tracked down, but they're easy. Happy coding!

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

Special thanks to @curiouskiwi for an assist. It was driving me nuts that the for loop in speller.c that calls check() wasn't executing. Now I know why.

You must log in to answer this question.

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