我有一个结构是一个节点,另一个是这些节点的列表。在列表结构中,它是一个节点数组,但它不是一个数组,而是一个指向具有整数大小的指针的指针:
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 **) 是指向 [array of] 指针的指针,指向 Node,因此您分配的数组将没有任何结构成员。
您应该使用 (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;
}
此外,C99 允许您创建可变大小的结构,因此您可以像这样初始化结构
typedef struct list {
int size;
Node table[0]
} List;
并根据需要在表中分配尽可能多的节点 malloc(sizeof(List) + sizeof(Node)*n);
关于c - 如何在 C 中初始化指向指针结构的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4022442/