-1
我有在pset5一些麻烦
负荷的,其实我不知道如何开始调试,我看过的教训了几次,现在我不会在任何地方得到..Pset5实现使用特里
当我运行speller.c它给我一个赛格故障,我跑调试器,它崩溃的For循环的beggining,这里如下我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#include "dictionary.h"
// default dictionary
#define DICTIONARY "dictionaries/large"
//created the struct node
typedef struct node
{
bool is_word;
struct node * paths[27];
}
node;
int letter = 0;
char * word = NULL;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char *word)
{
//todo
return false;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char *dictionary)
{
//opens dictionary for reading
FILE *fp = fopen(DICTIONARY, "r");
if (fp == NULL)
{
return false;
unload();
}
//creates the root of the trie
node *root = malloc(sizeof(node));
root -> is_word = false;
node * trav = root;
char * word = NULL;
//start reading the file
while (fscanf(fp, "%s", word) != EOF)
{
for (int i = 0; i < strlen(word); i++)
{
//assing wich path to take
char c = fgetc(fp);
if (isupper(c))
{
letter = tolower (c);
letter = letter -'a';
}
else if (isalpha(c))
{
letter = c;
letter = letter -'a';
}
else if (c == '\'')
{
letter = 26;
}
else if (c == '\0')
{
trav -> is_word = true;
}
if (trav -> paths[letter] == NULL)
{
node *new_node = malloc(sizeof(node));
if (new_node == NULL)
{
return false;
unload();
}
//point to new node
trav -> paths[letter] = new_node;
}
else
{
trav = trav -> paths[letter];
}
}
}
if (fscanf(fp, "%s", word) == EOF)
{
fclose(fp);
return true;
}
return false;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
// TODO
return 0;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
// TODO
return false;
}
我也不知道如何将new_node指向下一个新节点,以及我是否必须为它们指定不同的名称。例如,我要存储单词“foo”的,所以我读叫TRAV节点,进入路径[5](在F字母),检查它是否已经打开,如果不是(如果它是NULL)我创建了一个名为new_node和点TRAV节点 - >路径[5]吧,比我应该更新TRAV成为新的节点,所以其指向它自己的路[信]
与您的问题无关,但您确实知道'return'立即返回*?在return之后的同一个作用域中的任何代码都不会被执行,这就是所谓的*死代码*。如果你无法打开文件,在'load'函数中你有* dead code *。 –
至于你的问题,当你把它传递给'fscanf'时,'word'指向哪里? 'fscanf'不会为你分配内存。 –
对不起,我更新了代码指向单词,只是忘了发布在这里:char * word = NULL; –