1
Checking........................................................................:) dictionary.c, dictionary.h, Makefile exist
:) speller compiles
:( handles most basic words properly
   \ expected output, not standard error of "/opt/sandbox50/bin/run.sh: line 31: 215..."
:( handles min length (1-char) words
   \ expected output, not standard error of "/opt/sandbox50/bin/run.sh: line 31: 214..."
:( handles max length (45-char) words
   \ expected output, not standard error of "/opt/sandbox50/bin/run.sh: line 31: 213..."
:( spell-checking is case-insensitive
   \ expected output, not standard error of "/opt/sandbox50/bin/run.sh: line 31: 214..."
:( handles possessives properly
   \ expected output, not standard error of "/opt/sandbox50/bin/run.sh: line 31: 215..."
:( handles substrings properly
   \ expected output, not standard error of "/opt/sandbox50/bin/run.sh: line 31: 215..."

I spent a period of torture time these days in testing my C code, it drove me crazy. I have no idea what the error information means. This is part of my code in dictionary.c.

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

        node *hashtable[27];

        unsigned int wordsize = 0;

    bool load(const char* dictionary)
    {
        char strs[LENGTH+1];

        FILE *file = fopen(dictionary,"r");
        if (file == NULL)
        {
            printf("cannot open %s file.",dictionary);
            return false;
        }

        while (fscanf(file, "%s", &strs[0]) != EOF)
        {
            wordsize++;
            node *new_node = malloc(sizeof(node));
            strcpy(new_node->WORD,strs);

            int index = hashfun(new_node->WORD);

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

            new_node = NULL;
        }

        fclose(file);
        return true;
    }

int hashfun(const char *s)
{
    int index = 26;
    if (s[0] >= 97 && s[0] <= 122)
        return (s[0] - 'a');
    else 
        return index;
}

Is there any error or lines not standard in it? Thank you so much for your advices!

1 Answer 1

1

Okay, here's the thing: this is how you're inserting a new node into your hash table

int index = hashfun(new_node->WORD);

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

What if hashtable[index] is equal to NULL?

You'll definitely get a segfault for trying to access hashtable[index]->next.

The way you should insert a new node at the beginning of a list is

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

Watch section 7 for more information about this subject!

Also, array names decay to pointers. You could have just used strs instead of &strs[0] as an argument to fscanf (although I recommend you give it a more descriptive name).

You must log in to answer this question.

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