首页 > 解决方案 > CS50 的拼写器无法处理最基本的单词

问题描述

// Implements a dictionary's functionality

#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include "dictionary.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;

// Hash table
node *table[N];

//num of words
int NumOfWords = 0;

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

// Hashes word to a number
unsigned int hash(const char *word)
{
   int hash_index = 0;
   for(int i = 0; word[i] != '\0'; i++)
   {
       if(isalpha(word[i]))
       {
            hash_index += word[i];
       }
   }
   return hash_index % N;
}

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

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

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

错误消息是:[1]:https ://i.stack.imgur.com/pabnG.png

此外,valgrind 在第 110 行表示大小为 8 的无效读取(光标 = 光标-> 下一个;)它还区分大小写检查单词,这不是我想要的。我曾尝试使用 strcasecmp 但无济于事。我对stackoverflow还是新手,所以请原谅格式上的一些小错误。

标签: cdictionarycs50

解决方案


推荐阅读