0

所以有2个结构:

struct Morning { 
    int time;                        
    int day;                 
    struct Morning *next;   //pointer for the next node if there are any collisions     
};

struct Days_Hash_Table {
    int count;                     
    struct Morning **task; // array for the hash table
};

如何为 分配内存struct Morning **task?另外,如何定义数组大小?(大小始终存储在全局变量中,比如说array_size。)我尝试了以下操作:

struct Days_Hash_Table* table = malloc(sizeof(struct Days_Hash_Table)+ sizeof(struct Morning)*array_size);

例如,当我尝试访问数组时,table->task[0]->time = 0;我遇到了分段错误。解决这个问题的正确方法是什么?**task如果我更改为也会更容易*task[]吗?

谢谢!

4

1 回答 1

0

如果要分配显示方式,则需要将其声明为:

struct Days_Hash_Table {
    int count;                     
    struct Morning task[]; 
};

并分配:

struct Days_Hash_Table* table = malloc(sizeof(*table)+ sizeof(table -> task[0])*array_size);

编辑

struct Morning { 
    int time;                        
    int day;                 
    struct Morning *next;   //pointer for the next node if there are any collisions     
};


struct Days_Hash_Table {
    int count;                     
    struct Morning task[]; 
};


struct Days_Hash_Table*alloc(size_t array_size)
{
    struct Days_Hash_Table* table = malloc(sizeof(*table)+ sizeof(table -> task[0])*array_size);

    if(table)
    {
        for(size_t index = 0; index < array_size; index++)
        {
            table -> task[index].time = index + 1;
            table -> task[index].day = index + 100;
        }
    }
    return table;    
}

int main(void)
{
    struct Days_Hash_Table* table = alloc(20);

    if(table)
    {
        for(size_t index = 0; index < 20; index++)
        {
            printf("Time[%zu] = %d ", index, table -> task[index].time);
            printf("Day[%zu] = %d\n", index, table -> task[index].day);
        }
    }
    free(table)
;}

https://godbolt.org/z/e66vzq

于 2020-12-21T01:24:59.623 回答