【发布时间】:2016-07-18 13:18:57
【问题描述】:
编辑:所以,'index' 没有被返回到 0。那么。这修复了一个段错误。但仍然得到不同的段错误。正在努力。
node* new_node(void){
node* ptr = malloc(sizeof(node));
for (int i = 0; i<27; i++) {
ptr->next[i] = NULL;
}
return ptr;
}
bool load(const char* dictionary)
{
FILE* dict = fopen(dictionary, "r");
node* ptr = new_node;
char word[LENGTH+1];
int index = 0;
for (int c = fgetc(dict); c!=EOF; c = fgetc(dict)){
if(c!='\n'){
word[index]=c;
index++;
}
else {
for(int x=0; x<=index; x++){
int ch = (word[x] == '\'') ? 26 : tolower(word[x])-'a';
if (ptr->next[ch] == NULL){
ptr->next[ch] = new_node;
}
ptr = ptr->next[ch];
}
ptr->end=true;
}
}
return true;
}
我正在尝试为字典实现 trie 数据结构,但我的程序似乎在此函数的某处出现了段错误。即使在 GDB 的帮助下,我似乎也无法确定它,所以有人可以帮帮我吗?
节点定义如下:
typedef struct node{
bool end;
struct node* next[27];
} node;
字典文件:
a
aaa
aaas
aachen
aalborg
aalesund
aardvark
aardvark's
aardvarks
aardwolf
(...)
【问题讨论】:
-
另外,请务必检查 malloc 是否正确返回...
-
@Haris 为什么会这样?分配的内存不应该是节点对象的大小吗?
-
@Haris 分配指针似乎并不正确。他为什么要这么做? “确切地说,节点对象 ptr 的类型是节点 * 而不是节点”是什么意思。 malloc 返回一个指向分配对象的指针......所以你的意思是......?
-
for (char c = fgetc(dict); c!=EOF; c = fgetc(dict))应该是for (int c = fgetc(dict); c!=EOF; c = fgetc(dict))。您无法将char与EOF进行比较,因为EOF值可能无法由char值表示。 -
struct node* next[27];诶?为什么这个变量被称为 next?我以为这是某种链表? “下一个”应该是什么,某种查找表?这是一个链表吗?哈希表?
标签: c pointers segmentation-fault trie