2015-10-18 84 views
0

我一直在阅读,并且我认为由于在我的程序中使用它之前未分配指针而导致出现此错误。是这样吗?如果是这样,我会怎么做呢? 。(作业)打印结构对象时出现分段错误

的结构是在一个文件中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

'char * firstName;'和'char * lastName''在你尝试scanf到它们之前似乎没有任何分配:( –

+1

题外话,因为它是“解决我的错误代码”的问题,没有你的部分明确的理解....你应该编译所有的警告&debug info('gcc -Wall -Wextra -g'),使用调试器('gdb'),也许使用[valgrind](http://valgrind.org/)和[ASAN](https://en.wikipedia .org/wiki/AddressSanitizer)并阅读您正在使用的标准函数的文档('printf':'\ n'应该在控制字符串的末尾;'scanf':您应该检查扫描项目的计数) –

+0

我可以通过class [i] = Student_create();像这样吗? – Genesis

回答

1
  1. 分割falut我为指针

char *firstName; char *lastName;

这些由于没有内存分配s为指针,只是没有指向任何有效的存储位置。 使用 pointer = malloc(<number of character to store> * sizeof(char));

另外释放分配的存储器朝向端部,以避免内存泄漏。

+0

我目前正在和学生一起工作,所以这些都只是占位符信息抱歉,我怎么才能让他们指向有效的内存位置?malloc他们? – Genesis

+1

是先分配内存使用malloc使用malloc –

+0

我应该在我的Student_cre中使用malloc吃了功能? – Genesis