我有大量的嵌套结构,这使得无法分配此类空间并迫使我使用堆。但是我在使用时遇到了困难malloc
。问题的要点如下。
struct year_of_joining
{
struct district
{
struct colleges
{
struct departments
{
struct sections
{
struct students
{
int sex;
}student[100];
}section_no[8];
}department_no[17];
}college[153];
}dist[13];
};
如果我用
int main()
{
int i=0;
struct year_of_joining** year;
year = malloc(100 * sizeof(struct year_of_joining));
for (i = 0; i < 100; i++)
{
year[i] = malloc(sizeof(struct year_of_joining));
}
year[1]->dist[0].college[0].department_no[0].section_no[0].student[8].sex = 1;//works fine
printf("%d", year[1]->dist[0].college[0].department_no[0].section_no[0].student[8].sex);//prints 1
free(year);
return 0;
}
它工作正常,但是当我创建指向year之类的dist指针(如year_of_joining)并使用间接运算符时,它不会编译:
year[1]->dist[2]->college[0].department_no[0].section_no[0].student[8].sex = 9;//error C2039: 'dist' : is not a member of 'year_of_joining'
我该如何解决?我是否在正确的轨道上?
我认为您在这里偏离了轨道。
请注意,单个struct year_of_joining
数据约为100 MiB。一排100个这样的结构需要大约10 GiB的数据(并且仅记录学生的性别-根本没有其他信息)。
struct year_of_joining** year;
year = malloc(100 * sizeof(struct year_of_joining));
此内存分配为数百万个指针分配了足够的空间。您几乎可以肯定打算使用:
struct year_of_joining *year = malloc(100 * sizeof(struct year_of_joining));
struct year_of_joining *year = malloc(100 * sizeof(*year));
这分配了价值100年的结构。
但是,您似乎不太可能拥有13个学区,每个学区有153个学院,每个学院有17个系,每个系有8个科室,每个科系有100名学生。每年相当于2500万学生!
您将需要一个更加灵活的安排,其中每个结构都包含一个指向嵌套结构列表的指针,因此您可以拥有更大的部分,但是规模较小的学院等。它将需要按照以下方式进行更多工作:
struct students
{
char name[32];
int sex;
// ... and other data ...
};
struct sections
{
char name[32];
// ... and other data ...
int n_students;
struct students *students;
};
struct departments
{
char name[32];
int n_sections;
struct sections *sections;
}
struct colleges
{
char name[32];
// ... and other data ...
int n_departments;
struct departments *departments;
};
struct district
{
char name[32];
// ... and other data ..
int n_colleges;
struct college *colleges;
};
struct year_of_joining
{
int year;
// ... and other data ...
int n_districts;
struct district *districts;
};
即使这样感觉并不完全正确,但是如果仅因为一个部门只有一个部门并且仅招收十名学生(因为它是少数派利益部门),那它将是一种比原始数据更好的组织数据的方法,那么只为一个部分和十个学生分配足够的空间,而不是为800个学生和八个部分分配空间。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句