c - 在 c 中的拼写程序中实现多个函数会返回所有拼写错误的单词。在 cs50 pset5 拼写器中
问题描述
该代码实现了这些功能:
check()
:检查输入的单词是否在字典文件中,load()
:将整个字典加载到哈希表中,hash()
: 散列一个词,size()
: 返回整个字典的大小和unload()
: 释放所有使用的内存load()
。
问题是该函数load()
仅将文件字典中的第一个单词加载到哈希表中。
这是故障功能
// Represents a node in a hash table. length being the largest word in the dictionary
typedef struct node {
char word[LENGTH + 1];
struct node *next;
} node;
// Number of hashes in hash table represent the alphabet
const unsigned int N = 26;
// a count variable to pass to the size function
int count = 0;
// Hash table
node *table[N];
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary) {
int b = 0;
char *c = malloc((LENGTH + 1) * sizeof(char));
FILE *f = fopen(dictionary, "r");
while (fscanf(f, "%s", c) != EOF) {
// b is the hash number
b = hash(c);
if (table[b] == NULL) {
node *n = malloc(sizeof(node));
if (n == NULL) {
return false;
}
strcpy(n->word, c);
n->next = NULL;
table[b] = n;
count++;
return true;
} else
if (table[b] != NULL) {
node *n = malloc(sizeof(node));
if (n == NULL) {
return false;
}
strcpy(n->word, c);
n->next = table[b];
table[b] = n;
count++;
return true;
}
}
return false;
}
解决方案
问题是函数总是true
在将第一个单词插入哈希表后返回。在其他问题中,您忘记了 freec
和 close f
。
这是修改后的版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
node *table[N];
int count;
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary) {
char buf[LENGTH + 1];
FILE *f = fopen(dictionary, "r");
if (f == NULL)
return false;
// problem: how to prevent `fscanf` from storing too many characters to buf?
while (fscanf(f, "%s", buf) == 1) {
node *n = malloc(sizeof(node));
if (n == NULL) {
fclose(f);
return false;
}
strcpy(n->word, buf);
// b is the hash number
int b = hash(buf);
n->next = table[n];
table[b] = n;
count++;
}
fclose(f);
return true;
}
推荐阅读
- php - 在 Git Repo 上克隆最新提交的文件
- javascript - 影子 DOM 中的 GetElementById
- linux - 打印带有 n 行长段落的文本文件
- javascript - 从 5 分钟间隔到 20 分钟间隔过滤日期数组
- reactjs - 动态从 Firestore 中删除数据
- kotlin - Kotlin 不推荐使用的注解将其替换为类名
- python - 使用 Cython 编译多 python 文件并生成一个 so
- css - 如何使方形 div 适合父 div
- html - 具有滚动和自动大小列的表格
- wordpress - 使用借记卡或信用卡支付的 Woocommerce Paypal Pay 间歇性不显示