【发布时间】:2022-01-02 14:28:06
【问题描述】:
我的目标是打印struct中包含的学生数据
我的问题是为什么我无法从结构中打印出数据?
这是我的代码:
typedef struct _STUDENT{
char *fullname;
int ID;
float scores[6];
} STUDENT;
void input(STUDENT* student){
fflush(stdin);
printf("\nInput Student Fullname: ");
scanf("%s", &student->fullname);
printf("\nInput ID: ");
scanf("%s",&student->ID);
for(int i = 0; i < 6; i++){
printf("\nInput point for course %d: ", i+1);
scanf("%f",&student[i].scores);
}
}
void output(STUDENT* student){
printf("\nStudent Fullname: %s", student->fullname);
printf("\nStudent ID: %d", student->ID);
for(int i = 0; i < 6; i++){
printf("\nStudent Score: %f", student[i].scores);
}
}
int main(){
STUDENT* students;
int size;
printf("Enter number of student: ");
scanf("%d",&size);
students = (STUDENT*)calloc(size,sizeof(STUDENT));
for(int i =0;i<size;i++){
input(students+i);
}
for(int i =0;i<size;i++){
output(students+i);
}
return 0;
}
这是输出:
Student Fullname:?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Student ID: 50
Student Score: 0.000000
Student Score: 0.000000
Student Score: 0.000000
Student Score: 0.000000
Student Score: 0.000000
Student Score: 0.000000
在输出功能下,我尝试打印出一些数据,但没有一个被打印出来
【问题讨论】:
-
您不能将
scanf字符串转换为&student->fullname,这是零指针的地址(通过calloc 归零)。您必须在读入字符串之前为其分配空间,最好使用fgets而不是scanf以避免潜在的缓冲区溢出问题。 -
使用
-Wall作为编译器选项来启用许多警告,包括 printf 和 scanf 的参数输入错误(假设您使用的是 gcc 或 clang)。 -
您正在尝试将 ID 扫描为字符串,但您正在为
int提供存储空间,并将结果作为int读回。 -
@PaulHankin:您可以使用
%<maxlen>s指定最大字段宽度,以防止使用scanf的缓冲区溢出 -
&student[i].scores是属于ith 学生的分数数组的地址。相反,您似乎想要&student->scores[i]。 (或者,student->scores + i表示相同的意思。)