使用结构从动态数组的变量返回随机值

returning random values from variables of dynamic array with struct

我遇到以下问题..: 我 运行 我的代码,它可以正确读取任意数量的作者,但是当我继续将作者的全名和日期打印到屏幕上时,我得到(例如)这个:

Example console log

如您所见,名称的 string/char 值是正确的,但日期的整数值只是随机数..

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

typedef struct{
    char lastName[30];
    char firstName[30];
    Date birthday;
}Person;

int main(){

    //assigning memory dynamically to array of authors
    int n;
    printf("How many authors should be added to the archive?\n");
    scanf("%i", &n);

    //array of authors
    Person* authors = (Person*) calloc(n, sizeof(Person));

    //reading authors
    int i;
    for(i = 0; i < n; i++){
        addAuthor(authors, i);
    }

    //writing authors to screen
    for(i = 0; i < n; i++){
        printAuthor(authors[i]);
    }

    free(authors);
    return 0;
}

Date inputDate(){
    Date d;
    printf("Input year: ");
    scanf(" %s", &d.year);
    printf("Input month: ");
    scanf(" %s", &d.month);
    printf("Input day: ");
    scanf(" %s", &d.day);
    return d;
}

Person inputAuthor(){
    Person p;
    printf("\nInput last name: ");
    scanf(" %s", &p.lastName);
    printf("Input last name: ");
    scanf(" %s", &p.firstName);
    p.birthday = inputDate();
    return p;
}

void printAuthor(Person p){
    printf("\n%s, %s born %i.%i.%i", p.lastName, p.firstName, p.birthday.day, p.birthday.month, p.birthday.year);
}

void addAuthor(Person* p, unsigned u){
    p[u] = inputAuthor();
}

您读错了日期:

printf("Input year: ");
scanf(" %s", &d.year);
printf("Input month: ");
scanf(" %s", &d.month);
printf("Input day: ");
scanf(" %s", &d.day);

这些字段的类型为 int,但 %s 格式说明符需要一个指向 char 数组的指针。使用不正确的格式说明符调用 undefined behavior.

要读取整数值,请使用 %d 格式说明符。

printf("Input year: ");
scanf("%d", &d.year);
printf("Input month: ");
scanf("%d", &d.month);
printf("Input day: ");
scanf("%d", &d.day);