C动态结构错误

时间:2016-08-03 18:06:26

标签: c arrays pointers dynamic struct

#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); 

为什么会这样? 感谢

1 个答案:

答案 0 :(得分:1)

.运算符的优先级高于一元*(请参阅here)。首先(在解除引用之前)编译器试图在age中找到(array+i)字段,该字段不是结构,而是指针。
 您想要*(array+i).age(array+i)->age替换(*(array+i)).age