1

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

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

struct student s[10];

但是,当我尝试将其返回给 main 然后将其传递给生成函数时,会出现不兼容错误。我目前的努力如下。但是,如您所见,我的代码除了生成的最后一组记录(即 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;
}
4

2 回答 2

5

Your generate() function only ever accesses the first student structure in your array. You need to use that for loop index in there:

 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);
 }
于 2013-01-12T22:46:41.710 回答
1

Change generate to

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[i].id = (rand()%10 + 1);
       students[i].score = (rand()%(100 - 0 + 1) + 0);
       printf("%d, %d\n", students[i].id, students[i].score);
    }
}
于 2013-01-12T22:51:21.577 回答