2

我有一个结构是一个节点,另一个是这些节点的列表。在 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;
}

如何将每个“数组”的 MyDef *entry 和 Node *next 设置为 NULL?

4

2 回答 2

1

(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;
}

此外,C99 允许您制作可变大小的结构,因此您可以像这样初始化结构

typedef struct list {
    int size;
    Node table[0]
} List;

并使用 malloc(sizeof(List) + sizeof(Node)*n); 在表中分配尽可能多的节点。

于 2010-10-26T11:48:22.790 回答
0

First of all, it seems to me that you have an error in your code allocating the array: It should say sizeof(Node*) rather than sizeof(Node) as you want to allocate an array of pointers to Node not an array of Node objects.

Then you can iterate through the array list:

for ( unsigned i = 0; i < l->size; ++i )
{
    Node* node = l->table[ i ];
    node->entry = NULL;
    node->next = NULL;
}

Another hint: You really should check your initialization function against possibilities of memory leaks.

于 2010-10-26T09:56:47.977 回答