c - 如何在 C 中初始化指向指针结构的指针?

标签 c arrays pointers malloc calloc

我有一个结构是一个节点,另一个是这些节点的列表。在列表结构中,它是一个节点数组,但它不是一个数组,而是一个指向具有整数大小的指针的指针:

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/

相关文章:

c - 使用C在Linux中通过串口从SIM读取短信

c - 有没有办法将所有指向已释放内存的指针设置为 NULL?

c - c 错误消息中出现行尾错误,提示缺少;之后(标记

arrays - 为什么 Ruby 的 each_with_object 会将附加有 += 运算符的数据删除到数组备忘录中?

C++ 从文件中计算字符数组中的特定计数器

c - 在整数数组的情况下,指针减法究竟是如何工作的?

c++ - 使用递归在恒定空间和线性时间内向后打印链表

c++ - 数组操作的复杂性

c - 指向节点的双指针

c++ - 关于指针和什么是/不是指针的问题