c-使用数组并在结构中分配内存(灵活的数组成员)



所以有两个结构:

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[]会更容易吗?

谢谢!

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

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] = %dn", index, table -> task[index].day);
}
}
free(table)
;}

https://godbolt.org/z/e66vzq

最新更新