簡體   English   中英

在結構中分配雙指針結構?

[英]Malloc'ing a double pointer structure inside a struct?

C菜鳥在這里。 我正在嘗試初始化一個簡單的結構,如下所示:

typedef struct person_s {
    char *fname;                 ///< first name of the person
    char *lname;                 ///< last name of the person
    char *handle;               ///< handle of the person
    struct person_s **friends;  ///< dynamic collection of friends
    size_t friend_count;        ///< current number of friends
    size_t max_friends;         ///< current limit on friends
} person_t;

我想我理解對這個結構中的每個成員都使用 malloc,除了其中的雙指針朋友結構。 如何為這個雙指針分配內存?

這是我的其他數據成員的 malloc:

person_t *newperson(char *fn, char *ln, char *han){
    person_t *p = NULL;
    p = malloc(sizeof(person_t));

    p->fname = malloc(strlen(fn) +1);
    strcpy(p->fname, fn);

    p->lname = malloc(strlen(ln) +1);
    strcpy(p->lname, ln);

    p->handle = malloc(strlen(han) +1);
    strcpy(p->handle, han);

    p->*friends = malloc(sizeof(*friends));

    p->friend_count = malloc(2*sizeof(friend_count));
    p->friend_count = 0;

    p->max_friends = malloc(2*sizeof(max_friends));
    p->friend_count = 0;
}

編輯:我的錯,我忘了在初始化這個結構的函數中包含它。

Edit1:為了回應評論,我在這里試圖實現的是創建一個動態的朋友“數組”,由 p->friends 數據成員指向。 另外,我有一個動態哈希表,將它用作一個集合來放置所有與此人相關聯的朋友是否是個好主意? 指針和動態分配的概念對我來說仍然有些混亂,很抱歉造成誤解。

對於動態集合,單指針就足夠了:

struct person_s *friends; 

...

p->friends = malloc(max_friends * sizeof(struct person_s));

首先保持語法簡單,讓我們假設您將typedef ed struct person_s作為person

指向指針的指針與指向指針數組的指針相同。

因此,首先需要分配數組,然后需要分配數組中的各個元素。

這將分配數組:

friends = malloc(max_friends * sizeof(*friends));

這是有效的,因為friends**person類型,所以*friends必須是*person類型。

然后,您將需要一個for循環,在其中分配每個person

friends[i] = malloc(sizeof(**friends)); //or sizeof(person), same thing.

(我在發完問題后立即輸入了上面的內容,才發現問題在我有機會回答之前就關閉了。然后后來打開了問題,但一直沒有通知我。我發布它是因為我會討厭現在就扔掉它。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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