2016-08-03 49 views
0
#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int size,choice; 
    printf("student size:\n"); 
    scanf("%d", &size); 

    typedef struct 
    { 
     int age; 
     double gpa; 
     char name[]; 
    }STUDENT; 
    STUDENT *array = (STUDENT *) malloc(sizeof(STUDENT) * size); 
    printf("\n(1) Add a student\n(2) Delete a student\n(3) Save all students\n(4)Quit\n"); 
    scanf("%d",&choice); 
    while (choice != 4){ 
     switch (choice) { 
      STUDENT temp; 
      STUDENT *tempptr = &temp; 
      int cellNum; 
      case 1: 
       printf("Enter age gpa and name:\n"); 
       scanf("%d %f %s",&tempptr->age,&tempptr->gpa,&tempptr->name); 
       printf("Enter cell number:\n"); 
       scanf("%d", &cellNum); 
       if (cellNum > (size-1)){ 
        printf("Invalid cell number\n"); 
        break; 
       }else{ 
        *(array + cellNum) = temp; 
       } 
      case 3: 
       printf("stupid c syntax rules"); 
       FILE *p = fopen("students.txt","w"); 
       int i = 0; 
       for (i=0; i<size; i++){ 
        fprintf(p, "%d, %f, %s\n",*(array+i).age,*(array+i).gpa,*(array+i).name); 
       } 
     } 
     printf("\n(1) Add a student\n(2) Delete a student\n(3) Save all students\n(4)Quit\n"); 
     scanf("%d",&choice); 
    } 

    return 0; 
} 

得到錯誤:時的動態結構錯誤

main.c:40:56: error: request for member 'age' in something not a structure or union          
        fprintf(p, "%d, %f, %s\n",*(array+i).age,*(array+i).gpa,*(array+i).name);        
                 ^                
main.c:40:71: error: request for member 'gpa' in something not a structure or union          
        fprintf(p, "%d, %f, %s\n",*(array+i).age,*(array+i).gpa,*(array+i).name);        
                    ^            
main.c:40:86: error: request for member 'name' in something not a structure or union          
        fprintf(p, "%d, %f, %s\n",*(array+i).age,*(array+i).gpa,*(array+i).name); 

爲什麼會出現這種情況? 謝謝

+0

'char name [];'需要大小。 – BLUEPIXY

回答

1

.運算符比一元運算符*(請參閱here)更高的優先級。因此,首先(解除引用前)編譯器試圖在(array+i)中找到age字段,該字段不是結構,而是指針。
您想要用(array+i)->age(*(array+i)).age替換*(array+i).age

+0

謝謝,解決了錯誤!在執行scanf(「%d%f%s」,&tempptr-> age,&tempptr-> gpa,&tempptr-> name)之後,現在即時獲取segfault。你知道這個問題可能是什麼嗎?對不起,新增至C – throwawayguy

+0

這是一個不同的問題。 –

+0

我知道,我想我可能會問,因爲它似乎很小 – throwawayguy