使用struct

时间:2017-07-14 19:50:47

标签: c struct dynamic-arrays

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

Example console log

正如您所看到的,名称的字符串/ 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();
}

1 个答案:

答案 0 :(得分:1)

您正在错误地阅读日期:

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);