我一直在阅读,我认为由于在我的程序中使用它之前没有分配指针而得到此错误。是这样的吗?如果是这样的话我该如何去做呢? (家庭作业)
Struct位于文件data.h中
typedef struct student
{
char *firstName;
char *lastName;
int GPA;
float tuitionFees;
int numClass;
}Student;
这是在一个名为student.c的文件中。
Student Student_create()
{
Student *myStudent = malloc(sizeof(Student));
assert(myStudent != NULL);
printf("Please enter a name: ");
scanf("%20s",myStudent->firstName);
printf("\nPlease enter a family name: ");
scanf("%20s",myStudent->lastName);
printf("\nEnter number of enrolled classes: ");
scanf("%d",&myStudent->numClass);
printf("\nEnter students GPA: ");
scanf("%d",&myStudent->GPA);
printf("\nEnter tuition Fee: ");
scanf("%f",&myStudent->tuitionFees);
return myStudent;
}
void Student_print(Student *who)
{
fflush(stdout);
printf("First Name: %s\n, ",who->firstName);
printf("Last Name: %s\n", who->lastName);
printf("\tTuition Fees: %f\n, ",who->tuitionFees);
printf("Number of Courses: %d\n , ",who->numClass);
printf("GPA : %d\n, ",who->GPA);
}
我尝试访问它的主文件标记为col_personal.c
int main(int argc, char *argv[])
{
//This is for the input
int choice;
mainMenu();
return 0;
}
void mainMenu()
{
int choice = 0;
Student class[10];
int ssize = 0;
while(choice != 10){
printf("\n\n\n\t\t\t====School Database====\n");
printf(" 1. Add a new record\n");
printf(" 2. Print Students.\n");
scanf("%d",&choice);
//CHOICE ADD NEW RECORD.
if(choice == 1)
{
printf("1.Student\n");
fflush(stdin);
scanf("%d",&choice);
if(choice == 1){
printf("How many students would you like to input? ");
scanf("%d",&choice);
//Creates Students
for(int i=0; i<choice;i++){
class[i] = Student_create();
ssize = ssize + 1;
}
}
//PRINTING STUDENTS CHOICE 2
} else if (choice == 2){
for(int i=0; i < ssize;i++){
Student_print(class[i]);
}
答案 0 :(得分:1)
char *firstName;
char *lastName;
这些只是指向任何有效内存位置的指针。
使用
pointer = malloc(<number of character to store> * sizeof(char));
同时释放分配的内存,以避免内存泄漏。