[英]How to initialise a pointer to pointer struct in C?
我有一个结构,它是一个节点,另一个是这些节点的列表。 在列表结构中,它是一个节点数组,但不是数组,而是一个指向整数的指针:
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;
}
如何为每个“数组”将MyDef * entry和Node * next设置为NULL?
(Node **)是指向Node的[array of]指针的指针,因此您分配的数组将没有任何结构成员。
您应该使用(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;
}
所以从我的角度来看,正确的代码是:
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;
然后使用malloc(sizeof(List)+ sizeof(Node)* n)在表中分配任意数量的Node。
首先,在我看来,您在分配数组的代码中出现错误:应该分配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;
}
另一个提示:您确实应该检查初始化函数,以防内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.