gpt4 book ai didi

c - 嵌套结构 - 输入

转载 作者:行者123 更新时间:2023-11-30 19:10:04 25 4
gpt4 key购买 nike

我需要将名称输入到结构中的变量(名字*)与 malloc我不明白为什么编程无法运行。我插入名字(例如大卫)它应该获取名称并将其放入临时数组中然后调整指针first_name*的大小并将字符串 temp 复制到first_name*

有人可以帮助我理解为什么它不起作用吗?

查找函数“ReadPerson”。

typedef struct{
int day, month, year;
} Date;

typedef struct{
char *first_name, *last_name;
int id;
Date birthday;
} Person;

void ReadDate(Date *a)
{
printf("insert day, month, year\n");
scanf("%d%d%d", &a->day, &a->month,&a->year);
}

void ReadPerson(Person *b)
{
char temp_first_name[21];
char temp_last_name[21];

printf("insert first name:\n");
gets(temp_first_name);
b->first_name = (char*)malloc(strlen(temp_first_name)+1);
strcpy(b->first_name,temp_first_name);
//need to check malloc (later)

printf("insert last name:\n");
gets(temp_last_name);
b->last_name = (char*)malloc(strlen(temp_last_name)+1);
strcpy(b->last_name, temp_last_name);
//need to check malloc (later)

printf("insert id\n");
scanf("%d",&b->id);

printf("insert person's birthday:\n");
ReadDate(b);
}

谢谢。

最佳答案

i don't understand why to program is fail to run

嗯,这是因为您正在尝试替换不兼容的类型,而像样的编译器应该已经告诉您这一点。

让我们看一下函数void ReadPerson(Person *b)的结尾:

{
...
ReadDate(b); // error here
}

如您所见,b 的类型为 Person *,您将其传递给函数 void ReadDate(Date *a),该函数期望Date * 类型。

所以这可能是一个简单的拼写错误,只需更改为:ReadDate(&b->birthday);

关于c - 嵌套结构 - 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41895048/

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