')'令牌和变量未声明错误之前的预期表达式

时间:2017-12-04 02:48:32

标签: c struct malloc

这是我试图编写的程序:

#include<stdio.h>
#include<malloc.h>
struct student {
    char name[20];
    float point;
};
void inputlst (struct student *sv, int n){
    int i;
    for(i = 0; i < n; i++){
        puts("Name: "); gets((sv+i)->name);
        puts("Point: "); scanf("%f", &(sv+i)->point);
    }
}
void outputlst (struct student *sv, int n){
    int i;
    for(i = 0; i < n; i++){
        puts((sv+i)->name); printf("%f", (sv+i)->point);
    }
}
void main(){
    struct student *classA;
    int n;
    printf("No. of students: ");
    scanf("%d", &n);
    classA = (student*)malloc(n*sizeof(student));
    if(classA == NULL)
        puts("Could not provide dynamic memory");
    else{
        inputlst(classA, n);
        outputlst(classA, n);
    }
}

当我运行它时,我遇到了这些错误:

1/error: ‘student’ undeclared (first use in this function)
classA = (student*)malloc(n*sizeof(student));
          ^~~~~~~
2/error: expected expression before ‘)’ token
classA = (student*)malloc(n*sizeof(student));
                  ^

它是什么意思:&#34;'学生'未申报&#34;当我已经在void()函数中声明它以及我希望将哪个表达式放入指定位置的函数中时?

1 个答案:

答案 0 :(得分:0)

分配内存的正确方法是:

 struct student *students;
 students = malloc(sizeof(struct student) * n);

您没有创建typedef,因此需要使用struct关键字引用它。