繁体   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