首页 > 解决方案 > 在结构内分配双指针结构?

问题描述

这里是菜鸟。我正在尝试初始化一个简单的结构,如下所示:

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 数据成员指向。另外,我有一个动态哈希表,将它用作一个集合来放置所有链接到此人的朋友是否是一个好主意?指针和动态分配的概念仍然让我有些困惑,很抱歉造成误解。

标签: cstructmalloc

解决方案


单指针就足够动态收集了:

struct person_s *friends; 

...

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

推荐阅读