我想做的是使用一个结构函数,该函数采用学生结构中包含的值,创建一个学生结构,然后返回一个学生指针。所以基本上:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student_struct
{
char name[16];
int age;
float gpa;
}Student;
Student *makeStudent(char name[16], int age, float gpa)
{
Student *s = (Student *) malloc(sizeof(Student));
//FIXME: Make your code changes here....
strcpy(s->name, name);
s->age=age;
s->gpa=gpa;
return s;
}
//Display the values of all students in the class
void displayClass(Student classArray[], int size)
{
int i;
for(i=0;i<size;i++){
printf(" %s, %d, %.1f\n", classArray[i].name, classArray[i].age, classArray[i].gpa);
}
}
int main()
{
//FIXME: Implement make student function
Student *adam = makeStudent("adam", 18, 2.0);
Student *beth = makeStudent("beth", 19, 3.2);
Student *chris = makeStudent("chris", 18, 3.6);
Student *daphney = makeStudent("daphney", 20, 3.9);
Student *erin = makeStudent("erin", 19, 2.6);
const int CLASS_SIZE = 5;
Student classArray[CLASS_SIZE];
classArray[0] = *adam;
classArray[1] = *beth;
classArray[2] = *chris;
classArray[3] = *daphney;
classArray[4] = *erin;
displayClass(classArray, CLASS_SIZE);
//deallocate memory
free(adam);
free(beth);
free(chris);
free(daphney);
free(erin);
return 0;
}
我想得到的输出是:
adam, 18, 2.0
beth, 19, 3.2
chris, 18, 3.6
.... (continues from there)
但是,相反,我得到的是:
, 0, 0.0
, 0, 0.0
, 0, 0.0
, 0, 0.0
, 0, 0.0
我认为这与
有关Student *makeStudent(char name[16], int age, float gpa)
功能正常,但我不确定。有什么提示吗?找不到答案!