[英]Segmentation fault, initializing recursive struct in C
好的,我整理了问题代码的简化示例:
#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
新手,所以我完全不知道发生了什么。
sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));
有一个错误。
在32bit操作系统中, sizeof(Trie*)
将为4,因为Trie*
是一个指针,而在32bit操作系统中,指针的大小为4。您可以这样操作: sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.