c - 嵌套结构数组

标签 c struct malloc dynamic-memory-allocation

我有大量的嵌套结构,这使得我无法分配那种空间并迫使我使用堆。但是我在使用 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_of_joining 创建一个指向 dist 的指针并使用间接运算符时它不编译:

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 年的结构值(value)。

但是,您有 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 个学生和 8 个部门。

关于c - 嵌套结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30562227/

相关文章:

c - 如何正确地 malloc C 中的结构

C - 使用内部已存在的指针扩展结构数组

C、架构 x86_64 的 undefined symbol

c - 将数组和矩阵传递给函数作为 C 中的指针和指向指针的指针

c - 具有 void 函数的 libffi 段错误

c++ - 结构运算符重载

c++ - 同时声明和初始化一个结构/类数组

c - C 中的压栈、出栈操作

在C中创建单独的堆

c - 与子信号和父信号同步将接收到的信号与文件进行匹配