我的问题是,我需要存储许多课程,每门课程都有一个名称,并且一门课程中有多个部分,每个部分中的许多学生每个都有一个名称(显然),每个学生有许多类型为float
的作业。
到目前为止,我创建了一个嵌套结构:
struct Student {
float *Assignments;
};
struct Section {
char Student_Name[30];
struct Student *Students;
};
struct Course {
char Course_Name[10];
struct Section *Sections;
};
struct Test_Cases {
struct Course *Courses;
};
具有指向根结构的指针:
struct Test_Cases *ptr;
表面上分配了内存给根结构和课程:
ptr = (struct Test_Cases *)malloc(*Num_Cases * sizeof(struct Test_Cases));
ptr->Courses = (struct Course *)malloc(*Num_Courses * sizeof(struct Course));
我的解决方法是否正确?谢谢。
是的,似乎是正确的开始。
幸运的是,您的要求不涉及任何动态分配的多维数组,因为在C语言中这远非易事。
这里您只需要分配各种结构数组。有两种在C中分配数组的常用方法:
未初始化的内存:
struct Test_Cases* ptr = malloc(*Num_Cases * sizeof(struct Test_Cases));
或(恕我直言更好):
struct Test_Cases* ptr = malloc(*Num_Cases * sizeof(*ptr));
零初始化内存:
struct Test_Cases* ptr = calloc(*Num_Cases, sizeof(struct Test_Cases));
或:
struct Test_Cases* ptr = calloc(*Num_Cases, sizeof(*ptr));
[malloc
稍快一些,因为它跳过了0初始化部分,但是具有这种初始化可能有助于编写较短的代码,在这种情况下,应首选使用它。
对于所有这些结构,最好添加一个整数成员,其中包含为数组分配的元素数:
struct Student {
char Student_Name[30];
size_t Num_Assignments;
float *Assignments;
};
struct Section {
char Section_Name[30];
size_t Num_Students;
struct Student *Students;
};
struct Course {
char Course_Name[10];
size_t Num_Sections;
struct Section *Sections;
};
struct Test_Cases {
size_t Num_Courses;
struct Course *Courses;
};
[分配这些数组时,使用calloc()
获取零初始化内存并始终测试内存分配失败是更安全的方法:
#include <stdlib.h>
struct Test_Cases *allocate_test_cases(int Num_cases, int Num_courses) {
struct Test_Cases *ptr = calloc(Num_Cases, sizeof(*ptr));
if (ptr == NULL)
return NULL;
ptr->Num_Courses = Num_Courses;
ptr->Courses = calloc(Num_Courses, sizeof(*ptr->Courses));
if (ptr->Courses == NULL) {
free(ptr);
return NULL;
}
...
}