我在下面的函数allocate()的第一行收到错误“'struct'之前的预期表达式”。 我无法弄清楚为什么。

我应该说我的任务是使这个代码与提供的结构/函数头一起工作。

任何帮助深表感谢!

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <time.h>

struct student{
    int id;
    int score;
};

struct student* allocate(){
     /*Allocate memory for ten students*/
     struct student *stud =  malloc(10 * sizeof struct *student);
     assert (stud !=0);

     return stud;
}

void generate(struct student *students){
     /*Generate random ID and scores for ten students, ID being between 1 and 10, scores between 0 and 100*/
     srand(time(NULL));

     // Generate random ID's
     int i;
     for(i=0; i<10; i++){
        students[i].id = rand()*10+1;
     }

     //Generate random scores
     for(i=0; i<10; i++){
        students[i].score = rand()*10+1;
     }
}

void output(struct student* students){
     //Output information about the ten students in the format:

     int i;
     for(i=0; i<10; i++){
        printf("ID-%d Score-%d\n", students[i].id, students[i].score);
        }
}

void summary(struct student* students){
     /*Compute and print the minimum, maximum and average scores of the ten students*/
     int min = 100;
     int max = 0;
     int avg = 0;
     int i;
     for(i=0; i<10; i++){
        if(students[i].score < min){
            min = students[i].score;
        }
        if(students[i].score > max){
            max = students[i].score;
        }
        avg = avg + students[i].score;
    }
    avg = avg/10;
    printf("Minimum score is %d, maximum score is %d, and average is %d.", min, max, avg);

}

void deallocate(struct student* stud){
     /*Deallocate memory from stud*/
     free (stud);
}

int main(){
   struct student *stud = NULL;

    /*call allocate*/
    stud = allocate();

    /*call generate*/
    generate(stud);

    /*call output*/
    output(stud);

    /*call summary*/
    summary(stud);

    /*call deallocate*/
    deallocate(stud);

    return 0;
}

===============>>#1 票数:7 已采纳

你可能想写

sizeof(struct student)

代替

sizeof struct *student

===============>>#2 票数:1

你的问题是sizeof struct *student 在typename上使用sizeof运算符时,需要将typename括起来。 另外,正如Jonathan Leffler在对这个答案的评论中所指出的那样, *struct *student是错误的,并且在这段代码的上下文中使用struct student *是不正确的。 也许你的意思是: sizeof (struct student)

或者,您可以在表达式上使用sizeof ,而不需要括号。 这是首选,因为如果你选择改变stud的类型,那么当你这样做时你不需要替换额外的类型名: struct student *stud = malloc(10 * sizeof *stud);

  ask by Tanner translate from so

未解决问题?本站智能推荐: