【发布时间】:2015-08-14 05:56:06
【问题描述】:
我有大量嵌套结构,因此无法分配这种空间并迫使我使用堆。但是我在使用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;
}
它工作正常,但是当我创建一个指向 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声明不会创建嵌套结构。它只是在彼此内部声明了一堆结构类型。在 C 中声明struct内的类型而不创建命名数据字段是非法的 - 声明甚至无法编译。请提供更有意义的声明。究竟什么是嵌套的,嵌套的数据字段名称是什么? -
D的大小怎么可能是 120?它是一个指针和两个整数。并且结构 A、B 和 C 是空的,所以它们的大小应该很小。 -
@juanchopanza 120 是结构 D 的数组大小。
-
看起来像噩梦。
-
@solinvictus 也许您可以使用多个小型结构,并通过 malloc() famaily 函数动态分配内存。改进代码的设计和组织。
标签: c struct malloc dynamic-memory-allocation