【发布时间】:2019-05-06 21:58:35
【问题描述】:
我正在与学生一起创建一个数据库,我创建了一个struct Students
struct Students {
//struct specific for students
char first_name[30];
char last_name[30];
int ssn;
};
void add_student() {
//function to add students
int i, n;
struct Students *student;
printf("How many students are you adding");
scanf("%d", &n);
student = (struct Students *)malloc(n * sizeof(struct Students *)); //allocate the memory for n students
for (i = 0; i < n; i++) {
printf("Enter first, last and ssn respectively");
scanf(" %s ", &(student+i)->first_name); //adds first name to student i
scanf(" %s ", &(student+i)->last_name);// adds last name to student i
scanf(" %d ", &(student+i)->ssn); //adds ssn to student i
}
for (i = 0; i < n; i++) {
//print each of the students being added
printf("First name: %s\n ", (student+i)->first_name);
printf("Last name: %s\n ", (student+i)->last_name);
printf("ssn: %d\n ", (student+i)->ssn);
}
free(student); //free the memory used
}
预期:我正在尝试为数据库添加学生并打印它们 以确保它们实际上被写入结构。
实际:
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[30]’ [-Wformat=]
scanf(" %s ", &(student+i)->first_name);
【问题讨论】:
-
&不需要first_name和last_name。 -
是否需要免费(学生),因为当我运行程序时 *** `./Project' 中的错误:free():下一个大小无效(快速):0x0000000002133830 ***
-
该错误表明内存已损坏。您需要发布minimal reproducible example,包括您提供给程序的输入。
-
顺便说一句,
(student+i)->与student[i].相同,后者更容易阅读,imo。 -
并且不要强制转换 malloc。在 C 中它是不必要的,并且可以隐藏其他问题。