使用数组并在结构中分配内存(灵活的数组成员)
Use an array and allocate memory in a struct (Flexible array members)
所以有 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[]
会更容易吗?
谢谢!
如果你想分配你显示的方式,你需要声明为:
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)
;}
所以有 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[]
会更容易吗?
谢谢!
如果你想分配你显示的方式,你需要声明为:
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)
;}