【发布时间】:2021-11-26 08:49:59
【问题描述】:
这里是菜鸟。我正在尝试初始化一个简单的结构,如下所示:
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:为了响应 cmets,我在这里想要实现的是创建一个动态的朋友“数组”,由 p->friends 数据成员指向。另外,我有一个动态哈希表,将它用作一个集合来放置与此人相关的所有朋友是否是一个好主意?指针和动态分配的概念对我来说仍然有些混乱,很抱歉造成误解。
【问题讨论】:
-
您最多期望
max_friends朋友。因此,您需要为指向其他朋友的max_friend指针分配空间。p->friends = malloc(max_friends * sizeof(*person_s)) -
为什么你认为你需要在这里为
friends使用双指针? -
“我如何为这个双指针分配内存?” - 问题不在于如何。问题是为什么。这是一个 XY 问题。
-
另一件事,记得在发布之前最小化你的代码。你有很多不同的领域,只会让你的问题变得臃肿。并且 ptp 在结构中这一事实没有任何区别。
-
@klutt gotcha,谢谢!