1
返回動態數組變量的隨機值我有以下問題..: 我運行我的代碼,它可以正確讀取任意數量的作者,但是當我繼續將作者的全名和日期打印到我得到(例如)屏幕這樣的:從結構體
正如你所看到的名稱字符串/ 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();
}
'%s'用於讀取字符串,而不是整數。 –
2nd'printf(「Input last name:」);' - >'printf(「Input first name:」);' – BLUEPIXY