我工作的一本字典,其结构是:的malloc与多维数组
typedef union _dict {
union _dict * children[M];
list * words[M];
} dict;
初始化:
dict *d = (dict*) malloc(sizeof(dict));
我试图做到以下几点:
dict *temp;
temp = d;
temp=temp->children[0];
temp=temp->children[0];
first temp->children[0]
工程,但不是第二。我试图理解为什么。我认为这是一个内存分配问题。
编辑1: 我试过下面的代码:
dict *d = (dict*) malloc(sizeof(dict));
dict *temp;
temp = d;
dict *d2 = (dict*) malloc(sizeof(dict));
temp->children[0] = d2;
temp = temp->children[0];
temp = temp->children[0];
temp = temp->children[0];
即现在的作品,但我不明白为什么......我的意思是,我没有允许一些内存为下一个孩子。
编辑2: 所以现在,我想在我的算法中使用它。该代码块中我坚持如下:
list *l;
if (temp->words[occur] != NULL) {
/* ... */
}
else {
l = list_new();
temp->words[occur] = (list*) malloc(sizeof(list));
temp->words[occur] = l;
}
list_append(l,w);
list_print(l);
如果我这个块之前把temp->words[occur] = NULL;
,成功添加单词,而是一个新的列表中创建使用algorith各一次。我想将我的话添加到以前创建的列表中,假设它存在。
A bzero((void*)d, sizeof(dict));
指令在字典初始化后使用。
那是因为第一个孩子隐式创建了union_dict * children [M];但是该数组中的每个元素都不会自动分配。我相信是这个问题。因此,你的第二个使用的是没有为其创建“_dict”空间的“孩子”。 – Chad
在你的第二个代码块中:第一个赋值将用一个有效的“dict”填充“temp”。第二个将填充垃圾。第三个应该失败,因为垃圾中不存在“孩子”。 – Chad
因此,每次我探索下一个孩子时,我都必须为它分配一个字典? – kh4r4