Как исправить ошибки в коде "Speller" CS50 PSet-5 - PullRequest
0 голосов
/ 06 марта 2020

Так что мой код выдает много ошибок, когда я запускаю его с check50, и я хотел бы, чтобы кто-то указал мне, где мои ошибки. Заранее спасибо.

В этом блоке кода ошибки из check50. Мне нужен кто-то, чтобы вести или указать мне, где ошибка. Заранее спасибо! :)

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "dictionary.h"
#include <string.h>
#include <strings.h>

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Number of buckets in hash table
const unsigned int N = 26;
unsigned int key;
unsigned int word_count = 0;

// Hash table
node *table[N];

// Returns true if word is in dictionary else false
bool check(const char *word)
{
    unsigned int hashvalue = hash(word);
    node *cursor;
    cursor = table[hashvalue];
    while (cursor->next != NULL)
    {
        if (strcasecmp(word, cursor->word) == 0)
        {
            return true;
        }
        else
        {
          cursor = cursor->next;
        }
    }
    return false;
}

// Hashes word to a number
unsigned int hash(const char *word)
{
   unsigned int x = (unsigned int) word[0];
    if (x >= 'a' && x <= 'z')
    {
        x = x - 97;
    }
    else if(x >= 'A' && x <= 'Z')
    {
        x = x - 65;
    }
    return x;
}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    char w[LENGTH + 1];
    FILE *file = fopen(dictionary, "r");
    if (file == NULL)
    {
        return false;
    }
    while (fscanf(file, "%s", w) != EOF)
    {
        node *new_node = malloc(sizeof(node));
        if (new_node == NULL)
        {
            return false;
        }
        int index = hash(w);
        strcpy(new_node->word, w);
        if (table[index] == NULL)
        {
            table[index] = new_node;
            new_node->next = NULL;
        }
        else
        {
            new_node->next = table[index];
            table[index]->next = new_node;
        }
        word_count++;
    }
    fclose(file);
    return true;
}

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

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
    for (int i = 0; i < N; i++)
    {
        node *cursor = table[i];
        while (cursor != NULL)
        {
            node *tmp = cursor;
            cursor = cursor->next;
            free(tmp);
        }
    }
    return false;
}

check50 выбрасывает много ошибок.

:) dictionary.c, dictionary.h, and Makefile exist
:) speller compiles
:( handles most basic words properly
    expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:( handles min length (1-char) words
    expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:( handles max length (45-char) words
    expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:( handles words with apostrophes properly
    expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:( spell-checking is case-insensitive
    expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:( handles substrings properly
    did not find "MISSPELLED WOR..."
:| program is free of memory errors
    can't check until a frown turns upside down

1 Ответ

0 голосов
/ 06 марта 2020

Это неправильно:

        else
        {
            new_node->next = table[index];
            table[index]->next = new_node;
        }

Вы создали циклический список из new_node и table[index] и потеряли ссылку на остальную часть списка в этом узле.

Должно быть:

        else
        {
            new_node->next = table[index];
            table[index] = new_node;
        }

, чтобы поместить новый узел в начало списка на этом узле.

На самом деле вам даже не нужен if/else для вставки новый узел. Когда table[index] == NULL, присвоение new_node->next = table[index] совпадает с new_node->next = NULL, что вы делаете в блоке if. Поэтому просто используйте приведенный выше код безоговорочно.

В функции check() вы пропускаете последнее слово в списке.

    while (cursor->next != NULL)

должно быть

    while (cursor != NULL)
...