gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:48 26 4
gpt4 key购买 nike

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

Example console log

如您所见,名称的字符串/字符值是正确的,但日期的整数值只是随机数。

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

关于c - 使用结构从动态数组的变量返回随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45110629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com