我有一个结构是一个节点,另一个结构是这些节点的列表。在list结构中,它是一个节点数组,但它不是一个数组,而是指向一个大小为整数的指针:
typedef struct node {
struct node *next;
MyDef *entry;
} Node;
typedef struct list {
Node **table;
int size;
} List;
List *initialize(void)
{
List *l;
Node **n;
if ((l = (List *)malloc(sizeof(List))) == NULL)
return NULL;
l->size = 11;
/* I think this is correctly allocating the memory for this 'array' of nodes */
if ((n = (Node **)malloc(l->size * sizeof(Node))) == NULL)
return NULL;
/* Now, how do I set MyDef *entry and Node *next to NULL for each of the 'array'? */
l->table = n;
return l;
}
如何为每个'array'设置MyDef *条目和Node *旁边的NULL?
答案 0 :(得分:1)
(Node **)是指向Node的[array of]指针的指针,所以你分配的数组将没有任何struct成员。
你应该使用(Node *),然后你将指向Node结构的数组,或者分别分配每个Node,然后将指针放到你的数组中。
在你的情况下,标准C库中存在函数calloc():它在0的分配区域内(对应于(char / short / int / long)0,0.0和NULL)。
还有内存泄漏。
/* I think this is correctly allocating the memory for this 'array' of nodes */
if (... == NULL)
return NULL;
当数组分配失败时,您不会释放List,但会丢失指向它的指针。将其改写为:
/* I think this is correctly allocating the memory for this 'array' of nodes */
if ((n = (Node **)malloc(l->size * sizeof(Node))) == NULL) {
free(l);
return NULL;
}
所以从我的wiev来看,正确的代码是:
typedef struct node {
struct node *next;
MyDef *entry;
} Node;
typedef struct list {
Node *table; /* (!) single asterisk */
int size;
} List;
List *initialize(void)
{
List *l;
Node **n;
if ((l = (MList *)malloc(sizeof(List))) == NULL)
return NULL;
l->size = 11;
/* I think this is correctly allocating the memory for this 'array' of nodes */
if ((n = (Node *)calloc(l->size, sizeof(Node))) == NULL)
{
free(l);
return NULL;
}
/* Now, how do I set MyDef *entry and Node *next to NULL for each of the 'array'? */
l->table = n;
return l;
}
Futhermore C99允许您创建可变大小的结构,因此您可以初始化结构
typedef struct list {
int size;
Node table[0]
} List;
并根据需要在表中分配尽可能多的Node malloc(sizeof(List)+ sizeof(Node)* n);
答案 1 :(得分:0)
首先,在我看来,在分配数组的代码中有一个错误:它应该说sizeof(Node*)
而不是sizeof(Node)
,因为你想要分配一个指向Node的指针数组一个Node对象数组。
然后你可以遍历数组列表:
for ( unsigned i = 0; i < l->size; ++i )
{
Node* node = l->table[ i ];
node->entry = NULL;
node->next = NULL;
}
另一个提示:你真的应该检查你的初始化函数是否存在内存泄漏的可能性。