2011-11-22 69 views
3

我工作的一本字典,其结构是:的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));指令在字典初始化后使用。

+0

那是因为第一个孩子隐式创建了union_dict * children [M];但是该数组中的每个元素都不会自动分配。我相信是这个问题。因此,你的第二个使用的是没有为其创建“_dict”空间的“孩子”。 – Chad

+0

在你的第二个代码块中:第一个赋值将用一个有效的“dict”填充“temp”。第二个将填充垃圾。第三个应该失败,因为垃圾中不存在“孩子”。 – Chad

+0

因此,每次我探索下一个孩子时,我都必须为它分配一个字典? – kh4r4

回答

1

的问题在于,第一children作为指针创建一个dict,如:union _dict * children[M];但阵列中的每个元素是不会自动分配。因此,你的第二个电话正在使用一个没有为其创建空间的“孩子”。

如果你想让它正常工作,这样的事情应该解决这一问题:

typedef union _dict { 
    union _dict * children[M]; 
    list * words[M]; 
} dict; 

dict *temp = (dict*) malloc(sizeof(dict)); 

//allocate space for child, and reassign to it 
temp->children[0] = (dict*) malloc(sizeof(dict)); 
temp = temp->children[0]; 

//allocate space for child, and reassign to it 
temp->children[0] = (dict*) malloc(sizeof(dict)); 
temp = temp->children[0]; 

//etc... 

每个孩子都有被分配的内存,或者你只是得到垃圾和/或赛格故障。

+0

好吧,我明白了。我猜,对于'words'和相应的'malloc'呢? – kh4r4

+0

一般规则:如果它的动态创建,你需要分配和释放它的内存(像一些内置的一些例外)。 – Chad

+0

我的'dict d'初始化后,我使用'bzero((void *)d,sizeof(dict));'指令。我想知道什么是零接触和多少层次。 – kh4r4

2

起初在temp你有一个有效的指针指向一个对象(分配给malloc)。然后,您将一个未初始化的指针分配给temp,并尝试对其进行解除引用并带来预期的后果。

2

children永远不会被初始化,因此它包含之前在内存中的任何垃圾。在第一个temp = temp->children[0]之后,temp是指向未知领域的指针。

0
temp=temp->children[0]; 

您从未为temp->children[0]分配任何值。所以在这行代码之后,temp包含垃圾。

0

我认为第二次使用可能会给你segmantation故障。

看到

dict *d = (dict*) malloc(sizeof(dict)); // once you have malloc 



dict *temp; 
temp = d; 

temp=temp->children[0]; // that is going to use here 

使用第二次你还没有的malloc ..?右所以beffre以这种方式使用的,你应该喜欢的malloc

d->children[0] = (dict*) malloc(sizeof(dict)); 
+0

我现在已经为第一批孩子分配了内存(请参阅我的帖子上的编辑)。我不明白为什么它似乎为下一个孩子工作。 – kh4r4