c - 在 C 中分配内存和生成结构

标签 c memory-management structure

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

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

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;
}

最佳答案

您的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);
 }

关于c - 在 C 中分配内存和生成结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14298738/

相关文章:

javascript - 要求还是不要求?

solr - Solr文档带有子元素?

c - 如何从 ASN1 创建 .DER

c++ - 指针 : p++ & p+1

c++ - 最大 malloc 大小低于预期

c++ - 多维数组的动态内存分配背后的算法是什么?

java - Java中,空的HashMap空间分配

c - 使用另一个函数查找最大数字

c - sprintf 没有给出预期值

ios - 如何在 Swift 中将 Json 模型数据存储和提取到 Coredata