好的,我整理了一个问题代码的简化示例:
#include "stdio.h"
#include "string.h"
struct Trie{
//Holds sub-tries for letters a-z
struct Trie *sub[26];
//Is this a substring, or a complete word?
int is_word;
};
typedef struct Trie Trie;
Trie dictionary;
int main(int argc, char *argv[]){
//A list of words
char *words[7] = {"the","of","and","to","a","in","that"};
//Add the words to the Trie structure
int i=0, wordlen;
Trie *sub_dict;
for (;i<7; i++){
//Reset
printf("NEW WORD\n");
sub_dict = &dictionary;
//Add a word to the dictionary
int j=0, c;
while (c = words[i][j], c != '\0'){
printf("char = %c\n",c);
//Initialize the sub-Trie
if (sub_dict->sub[c-97] == NULL)
sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));
//Set as new sub-trie
sub_dict = sub_dict->sub[c-97];
j++;
}
sub_dict->is_word = 1;
}
}
基本上,我有一个 Trie 数据结构,其中包含字母“a”到“z”。我有一个应该添加到while
循环中的单词列表。不幸的是,我在循环的不同点遇到了分段错误(取决于我何时运行它)。
我猜这个问题与这条线有关,
sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));
但我是新手C
,所以我完全不知道发生了什么。