我遇到以下问题..: 我运行我的代码,它正确地读取了任意数量的作者,但是当我继续将作者的全名和日期打印到屏幕上时,我得到了(例如)这个:
正如您所看到的,名称的字符串/ 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();
}
答案 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);