gpt4 book ai didi

c - 尝试输入一个结构,第一次很好用,第二次就崩溃了

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:31 24 4
gpt4 key购买 nike

你好,我正在输入一个有 child 的家庭的结构,这两个结构:

typedef struct person {
int id;
char* firstName;
int age;
}person;

typedef struct family {
char* lastName;
person father, mother;
person* children;
int numChildren;
}family;

编辑:这是编辑过的函数,它仍然崩溃:

int initializeHouse(family **pdata)
{
char temp[SIZE];
int size, i, j;
printf("enter the number of families\n");
scanf("%d", &size);
*pdata = (family*)malloc(sizeof( family)*size);
for (i = 0; i<size; i++)
{
printf("Please enter the last name\n");
scanf("%s", temp);
(*pdata)[i].lastName = (char*)malloc(sizeof(char)* (strlen(temp) + 1));
strcpy(pdata[i]->lastName, temp);
printf("Enter the fathers first name\n");
scanf("%s", temp);
initPerson(temp, &pdata[i]->father.firstName);
printf("enter the fathers ID\n");
scanf("%d", &pdata[i]->father.id);
printf("Enter the fathers age\n");
scanf("%d", &pdata[i]->father.age);
printf("Enter the mothers first name\n");
scanf("%s", temp);
initPerson(temp, &pdata[i]->mother.firstName);
printf("enter the mothers ID\n");
scanf("%d", &pdata[i]->mother.id);
printf("Enter the mothers age\n");
scanf("%d", &pdata[i]->mother.age);
printf("enter the number of children");
scanf("%d", &pdata[i]->numChildren);
(*pdata)[i].children= (person*)malloc(sizeof(person)*(pdata[i]->numChildren));
for (j = 0; j<pdata[i]->numChildren; j++)
{
printf("enter the kids name\n");
scanf("%s", temp);
initPerson(temp, &pdata[i]->children[j].firstName);
printf("enter the kids ID\n");
scanf("%d", &pdata[i]->children[j].id);
printf("Enter the kids age\n");
scanf("%d", &pdata[i]->children[j].age);

}
}
return size;
}

void initPerson(char* str, char** fam)
{
*fam = (char*)malloc(sizeof(char)*(strlen(str) + 1));
strcpy(*fam, str);
}

编辑:我更改了代码,但它仍然不起作用,它需要我写一些描述,所以在这里..

最佳答案

  int main() {
int size;
family *a = NULL;
size=initializeHouse(&a);
}

声明一个指向结构的指针。当你传递它的地址时

size = initializeHouse(&a);

函数将它作为一个family**

获取

好的,到目前为止,我们都在同一个页面上。当您分配该指针的目标时

*pdata = malloc(sizeof(family) * size);

然后 *pdata 指向分配的结构数组,而不是指向这些结构的指针。每个结构体都通过(*pdata)[i]访问,也就是说->解引用双指针pdata得到数组第一个元素的地址,然后访问带下标的数组元素。

所以你的作业应该是

(*pdata)[i].lastName = malloc(sizeof(char)* (strlen(temp) + 1));

您使用点 . 运算符访问成员,因为下标访问的结果是结构,不是指向结构的指针。

关于c - 尝试输入一个结构,第一次很好用,第二次就崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48450201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com