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));
推荐阅读
- ios - 如何使用 swiftUI 更改键盘以反映段选择的输入类型?
- microsoft-graph-api - 图形订阅测试版 - AdditionalData
- python-3.x - 为pygame项目随机化背景音乐
- flutter - 在颤振应用程序中获取浮动操作按钮错误
- angular - 为什么没有调用函数?(在 Ionic & Angular 框架中)
- reactjs - 如何将数字作为道具传递给样式化组件?
- laravel - Laravel 助手
- java - 为什么这个 JAVA 端点没有向客户端返回详细的错误消息?
- python - 如何从先前分配的索引中获取值
- reactjs - 从 Blazor 服务器调用 React App.Render