gpt4 book ai didi

c - 如何创建一个修改结构体的函数

转载 作者:行者123 更新时间:2023-12-03 03:30:30 24 4
gpt4 key购买 nike

我正在制作一个程序,使用结构将学生成绩放入数组中作为期末练习。我需要创建一个函数来检查数组中是否还有任何位置,如果没有,则数组的大小需要加倍,然后需要将成绩添加到下一个可用位置。如果数组有空缺职位,则应将等级值添加到下一个可用职位。每当数组发生更改时,grades_array_pos 和grades_array_size 都必须使用正确的值进行更新。我对 C 还很陌生,我很难理解如何做到这一点。所有这些都必须仅使用基本变量、for 和 while 循环,并以非常基本的方式完成。

struct student_grades
{
int student_id;
int *grades_array[10];
int grades_array_pos;
int grades_array_size;
};
void add_grade(struct student_grades * student, int assignment_grade){

}

最佳答案

这是一项关键但简单的技能,每个人都需要掌握。基本方法是保持变量保存当前分配的元素数量和使用数量的计数器。然后循环填充你的数组。在循环的开始处,检查是否if (used == allocate)来确定是否需要重新分配。

如果需要重新分配,则使用 TEMPORARY 指针,调用 realloc 并将分配的元素数量加倍。验证 realloc 是否成功,否则,请中断填充数组的循环(不要退出程序),因为指向数组的原始指针仍然指向 realloc< 之前的有效数据 尝试。

如果realloc成功地将新大小的内存块分配给原始指针,则使用新的已分配元素计数更新变量 - 并继续,根据需要重复。示例:

#define NSTRUCT 8    /* initial number of struct to allocate for array */
...
size_t allocated = NSTRUCT, /* holds current number of elements allocated */
used = 0; /* holds current number used/filled */
struct student_grades *grades = malloc (allocated * sizeof *grades);

if (!grades) {
perror ("malloc-grades");
return 1;
}

while (/* loop to fill struct array */) {

if (used == allocated) { /* check if realloc needed */
/* always realloc using a TEMPORARY pointer */
void *tmp = realloc (grades, 2 * allocated * sizeof *grades);
if (!tmp) { /* validate reallocation */
perror ("realloc-grades");
break; /* don't exit, original pointer still good */
}
grades = tmp; /* assign reallocated block to grades */
allocated *= 2; /* update allocated size */
}

/* fill next element -- keep going.... */
used++;
}

仔细检查一下,如果您仍有疑问,请告诉我。

关于c - 如何创建一个修改结构体的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55755111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com