我需要将名称输入到结构中的变量(名字*)
用一个malloc
我不明白为什么编程无法运行。
即时通讯插入名称(例如David)
它应该获取名称并将其放入临时数组
然后调整指针的大小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);
}


谢谢。

最佳答案

我不明白为什么程序无法运行


好吧,这是因为您正在尝试替换不兼容的类型,并且不错的编译器应该已经告诉您了。

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

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


如您所见,b的类型为Person *,并将其传递给需要void ReadDate(Date *a)类型的函数Date *

因此,这可能是一个简单的错字,只需更改为ReadDate(&b->birthday);

08-05 11:08