簡體   English   中英

malloc與多維數組

[英]malloc with a multidimensional array

我正在編寫一個字典,其結構是:

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; 在此塊之前,單詞已成功添加,但每次使用算法時都會創建一個新列表。 我想將我的話添加到先前創建的列表中,假設它存在。

一個bzero((void*)d, sizeof(dict)); 在dict初始化之后使用指令。

首先在temp你有一個指向對象的有效指針(用malloc分配)。 然后,為temp分配一個未初始化的指針,並嘗試使用預期的結果取消引用它。

children永遠不會被初始化,所以它包含之前記憶中的垃圾。 在第一個temp = temp->children[0] ,temp是指向未知區域的指針。

問題在於第一個children被創建為指向dict的指針,如: union _dict * children[M]; 但是該數組中的每個元素都不會自動分配。 因此,您的第二個調用是使用沒有為其創建dict空間的“子”。

如果你想讓它正常工作,這樣的事情應該解決問題:

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...

每個孩子都必須分配內存,否則你只會得到垃圾和/或seg故障。

temp=temp->children[0];

你永遠不會為temp->children[0]賦值。 所以在這行代碼之后, temp包含了垃圾。

我認為第二次使用可能會給你分割錯誤。

看到

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 ..? 對你來說,你應該像malloc那樣使用beffre

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM