c - 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还是新手,所以请原谅格式上的一些小错误。
解决方案
推荐阅读
- json - NewtonSoft.Json 为所有人返回 null
- python - ImportError:导入_sqlite3时DLL加载失败:找不到指定的模块
- javascript - 在 JS 中装饰函数或对象
- nginx - 带有拆分客户端的 nginx A/B 测试
- python - 如果我使用网格搜索 cv,是否需要做 CV?
- variadic-functions - 通过 JNA 从 Java 调用 C varargs 函数
- python - Django rest 框架 - 包括一个用于访问授权的 api 密钥
- java - Azure/IntelliJ 使用 Cucumber 显示 runScenario 而不是实际测试名称
- csv - 如何在 Azure 数据工厂中逐行读取 csv 文件数据并将其存储在变量中
- node.js - 无法访问的主机:此服务在“ap-south-1”区域可能不可用