簡體   English   中英

如何在C中初始化指向struct的指針?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM