C:如何将指针存储在另一个结构内的动态数组中?
我的想法是拥有一个结构 Person
,该保留一个人的数据和结构 family
,其中包含家庭成员的数量和一个带有指针的数组。这些人应在运行时动态收集,存储在堆上, family
struct应包含这些人的一系列指针(成员
)。
现在,我对这个动态数组遇到了一些麻烦,想知道如何正确分配内存并将这些指针添加到数组中。
这是我当前的代码段:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
typedef struct Person{
int age;
char first_name[256];
char last_name[256];
} Person;
typedef struct {
size_t number_members;
Person **members;
} Family;
void init_person(Person *p);
void add_person_to_family(Family *f, Person *p);
void print_person(Person *p);
int main() {
size_t number_members = 2;
Family *f = calloc(1, sizeof(Family));
for (int i = 0; i < number_members; ++i) {
Person *p = calloc(1, sizeof(Person));
init_person(p);
add_person_to_family(f, p);
}
for (size_t i = 0; i < f->number_members; ++i) {
print_person(*f[i].members);
}
return 0;
}
void init_person(Person *p)
{
printf("Enter first name: \n");
scanf("%s", p->first_name);
printf("Enter last name: \n");
scanf("%s", p->last_name);
printf("Enter age: \n");
scanf("%i", &p->age);
}
void add_person_to_family(Family *f, Person *p)
{
f->number_members++;
f = realloc(f, sizeof(size_t) + (f->number_members) * sizeof(Person *));
f->members = realloc(f->members, (f->number_members) * sizeof(Person *));
f->members = p;
}
void print_person(Person *p)
{
printf("Age: %d\n", p->age);
printf("First Name: %s\n", p->first_name);
printf("Last Name: %s\n", p->last_name);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
上面的线毫无意义,需要删除。
family
是一个单个结构,其大小永远不会改变,无论其某些字段是否指向数组。它包含size_t
字段和指针字段。两者的尺寸都是恒定的。您无需realloc
it。顺便说一句,struct
的大小不是其字段大小的总和。上面的行是一个错误。
f-&gt;成员
指向Person
的一系列指针。您想更新该数组的元素。通常使用[]
运算符访问数组元素。该行应确定应保留什么
i
作为练习。这也是一个错误。
f
不是数组,也不指向数组元素,因此f [i]
不是您想要的。它是单个struct
的指针。使用- &gt;
运算符访问单个结构的字段。成员
是应该索引的。您需要demo
还有其他问题,例如不安全使用
scanf
和不检查库函数的返回值包括但不限于 realloc 。The line above makes no sense whatsoever and needs to be just deleted. A
Family
is a single struct, its size never changes, whether or not some of its fields point to arrays. It contains asize_t
field and a pointer field. Sizes of both are constant. You never need torealloc
it. By the way, the size of astruct
is not the sum of sizes of its fields.The line above is an error.
f->members
points into an array of pointers toPerson
. You want to update an element of that array. An array element is normally accessed with the[]
operator. The line should beDetermining what
i
should be is left as an exercise.This is also an error.
f
is not an array and does not point to an array element, sof[i]
is not what you want. It is a pointer to a singlestruct
. Fields of a single struct are accessed with the->
operator.members
is the one that should be indexed. You needDemo
There are other problems, like unsafe use of
scanf
and not checking return values of library functions including, but not limited to, realloc.