在C中分配内存并生成结构

use*_*050 1 c memory-management structure

我正在尝试通过Kernighan的书"C编程语言"来教我自己C为今年春天的数据结构类做准备(C是必需的先决条件),但我仍然坚持如何处理多个结构以及如何存储倍数以便稍后用于计算和输出.我为与学生记录相关的结构编写了一些代码,其中包含id和分数的变量.函数名称和参数必须保持原样,注释描述每个函数应该执行的操作.

所以这就是我尝试过的.我想在分配函数中为十个学生设置一个结构数组,如下所示:

struct student s[10];
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将其返回到main然后将其传递给generate函数时,我会遇到不兼容错误.我目前的努力如下.但是,正如您所看到的,我的代码无法存储除最后一组记录(即student.id和student.score)之外的任何内容.很明显,我错过了一个关键组件,这使我无法生成随机的唯一学生ID,因为我无法检查新的ID与之前的ID.我也无法继续编写函数来计算学生成绩.任何建议,将不胜感激.提前致谢.

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

struct student{
int id;
int score;
};

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

     /*return the pointer*/
     return s;
}

void generate(struct student* students){
 /*Generate random ID and scores for ten students, ID being between 1 and 10, scores between 0   and 100*/
   int i;
   for (i = 0; i < 10; i++) {
       students -> id = (rand()%10 + 1);
       students -> score = (rand()%(100 - 0 + 1) + 0);
       printf("%d, %d\n", (*students).id, (*students).score);
    }
}

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 deallocate*/
   deallocate(stud);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

Car*_*rum 5

您的generate()函数只能访问student数组中的第一个结构.你需要for在那里使用那个循环索引:

 for (i = 0; i < 10; i++)
 {
     students[i].id = (rand()%10 + 1);
     students[i].score = (rand()%(100 - 0 + 1) + 0);
     printf("%d, %d\n", students[i].id, students[i].score);
 }
Run Code Online (Sandbox Code Playgroud)