我的任务是创建一个功能齐全的拼写检查,我想我有一个以上的错误,我的代码,这是造成很多困难,当试图 Package 我的头周围到底是什么导致所有的皱眉check 50. check 50只说我的代码编译,其他一切都是皱眉,我认为我的程序可能在执行check函数时退出,因为size和unload没有运行时间。我还得到了运行时的退出代码1,不过,我可能会wayyy小康,因为这是我的第一个编程课程。任何提示,帮助或指针在正确的方向将massivly appriciated!
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include "dictionary.h"
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
} node;
// TODO: Choose number of buckets in hash table
const unsigned int N = 1000;
// Hash table
node *table[N];
bool check(const char *word)
{
// hash word
int x = hash(word);
// create cursor, set to first item in linked list
node *cursor = table[x];
// loop over hash tables
while (cursor != NULL)
{
if (strcasecmp(word, cursor->word) == 0)
{
return true;
}
cursor = cursor->next;
}
return false;
}
int dictionary_size = 0; // global variable for size of dictionary, used in multiple functions
unsigned int hash(const char *word)
{
int value = 0;
// hash function using math of all leters
// loop over every word
for (int i = 0; i < strlen(word); i++)
{
// convert to lower case for ascii values, removes case sensitive problem
value += tolower(word[i]); // sum of ascii values of word
}
return value % N; // return index for word
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
// TODO
// array to store words from dictionary
char word[LENGTH + 1];
// open dictionary file
FILE *d = fopen(dictionary, "r");
if (d == NULL)
{
return false;
}
// read strings from file repeat for each word in dictionary , similar loop to recover.c
while (fscanf(d, "%s", word) != EOF)
{
// keep track of dictionary size
dictionary_size++;
// create new node
node *n = malloc(sizeof(node));
if (n == NULL)
{
return false;
}
// store word in array
strcpy(n->word, word);
n->next = NULL;
// hash word
int x = hash(word);
// set pointers to correct order
n->next = table[x];
table[x] = n;
}
fclose(d);
return true;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
return dictionary_size;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
// loop over hash tables
for (int j = 0; j < N; j++)
{
// initialise cursor for local scope
node *cursor = table[j];
// traverse linked list
while (cursor != NULL)
{
node *tmp = cursor;
cursor = cursor->next;
free(tmp);
return true;
}
}
return false;
}
1条答案
按热度按时间gblwokeq1#
来自注解:
函数
unload
释放一个节点,然后释放return
(到speller的调用)。该函数在释放所有节点(即完成while循环)之前不会返回。