问题描述
我正在创建一个程序,该程序在返回主菜单之前获取用户输入并将其放入名为 Student 的结构中。从主菜单中,您可以添加另一个学生。这有效,但是当我尝试打印已添加到结构数组的所有学生数据时,它只打印添加的最后一个学生数据。
这是结构:
struct Student
{
char* firstName;
int age,cuid;
float GPA;
};
这就是我在 main 中为数组分配空间的方式:
struct Student* studentArray = malloc(*recordMaxPtr * sizeof(struct Student));
// Gets info and adds student to the array of structs
void addStudents(struct Student* s,int *numStudents)
{
// Allocate memory for the first name
char *firstName = (char*) malloc(25*sizeof(char));
// Gets the name of student
printf("What is the name of the student you'd like to add? ");
gets(s->firstName);
printf("\n"); // blank line
// Gets age of student
printf("How old is the student? ");
scanf("%d",&s->age);
printf("\n"); // blank line
// Gets CUID
printf("What is his / her CUID number? ");
scanf("%d",&s->cuid);
printf("\n"); // blank line
// Gets GPA
printf("What is the student's GPA? ");
scanf("%f",&s->GPA);
printf("\n"); // blank line
}
// Sorts the array and then lists all of the saved students
void printStudents(struct Student* s,int *numStudents)
{
//bsort();
for (int i = 0; i < *numStudents; i++)
{
printf("Student #%d\n",i + 1);
printf(" Student's Name: %s\n",s[i].firstName);
printf(" Age: %d\n",s[i].age);
printf(" CUID: %d\n",s[i].cuid);
printf(" GPA: %2f\n",s[i].GPA);
}
}
我想尝试使用 for 循环来一次性收集我需要的所有学生数据,但这是一个学校项目,我不允许这样做。我一直在尝试解决这个问题,但我在做什么方面遇到了困难。我最好的猜测是,每次您将新学生输入数组时,数据都会被覆盖,但我不知道如何解决这个问题。
解决方法
您为名字分配了内存,但没有将其保存在任何地方。您必须将地址存储到结构中。
// Allocate memory for the first name
char *firstName = (char*) malloc(25*sizeof(char));
s->firstName = firstName; // add this
另外还有一些事情要做,以获得更好的代码:
- 检查
malloc()
是否成功 - 检查
scanf()
是否成功 - 将
gets()
替换为fgets()
并移除换行符(gets()
具有不可避免的缓冲区溢出风险并已从新的 C 规范中移除) - 移除
malloc()
(c - Do I cast the result of malloc? - Stack Overflow) 的结果转换