当我运行它时会出现Segmentation故障,我真的很感激指出我做错了什么。
对于那些在cs50标签之外看到这个的人,我试图加载一个字典(在加载中),比较字符串和字典中的单词(在检查中),并卸载字典(在卸载中)。 / p>
这是我到目前为止所写的:
#include <stdbool.h>
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <ctype.h>
#include "dictionary.h"
#define HASH_MAX 27
/**
* Returns true if word is in dictionary else false.
*/
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
node *hashtable[HASH_MAX];
int count = 0;
int hash(string word)
{
int num = 0;
for(int i = 0; word[i] != '\0'; i++)
{
num += word[i];
}
return num % HASH_MAX;
}
bool check(const char *word)
{
char WordCopy[strlen(word) + 1];
strcpy(WordCopy, word);
for(int i = 0; i < strlen(WordCopy); i++)
{
tolower(WordCopy[i]);
}
node *cursor = hashtable[hash(WordCopy)];
while(cursor != NULL)
{
if(strcmp(cursor -> word,WordCopy) == 0)
{
return true;
}
else
{
cursor = cursor -> next;
}
}
return false;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char *dictionary)
{
node *head = hashtable[0];
FILE *file = fopen(dictionary, "r");
string word = NULL;
node *new_node = malloc(sizeof(node));
if(file == NULL)
{
return false;
}
while(fscanf(file, "%s", word) != EOF)
{
if(new_node == NULL)
{
unload();
return false;
}
else
{
strcpy(new_node -> word, word);
new_node -> next = head;
head = hashtable[hash(new_node -> word)];
}
fclose(file);
count++;
return true;
}
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
return count;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
node *head = hashtable[0];
node *cursor = head;
while(cursor != NULL)
{
node *temp = cursor;
cursor = cursor -> next;
free(temp);
}
return false;
}