gpt4 book ai didi

c - 段错误,在 C 中初始化递归结构

转载 作者:太空宇宙 更新时间:2023-11-04 07:31:51 25 4
gpt4 key购买 nike

好的,我整理了一个问题代码的简化示例:

#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;
}
}

基本上,我有一个包含字母“a”到“z”的 Trie 数据结构。我有一个应该添加到 while 循环中的单词列表。不幸的是,我在循环的不同点遇到了段错误(取决于我运行它的时间)。

我猜这个问题与线路有关
sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));
但我是 C 的新手,所以我完全不知道发生了什么。

最佳答案

sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));有错误。

sizeof(Trie*) 在 32bit os 中会是 4,因为 Trie* 是一个指针,在 32bit os 中指针的大小是 4。你可以这样做:sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie));

关于c - 段错误,在 C 中初始化递归结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13042385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com