2020年12月20日星期日

Use an array and allocate memory in a struct (Flexible array members)

So there are 2 structs:

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  };  

How can I allocate memory for the struct Morning **task? Also, how can I define the array size ?(the size is always stored in a global variable, say array_size.) I tried the following:

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

and when I tried accessing the array, for example, table->task[0]->time = 0; I got segmentation fault. What is the right way of approaching this? Also will it be easier if I change **task to *task[]?

Thanks!

https://stackoverflow.com/questions/65386344/use-an-array-and-allocate-memory-in-a-struct-flexible-array-members December 21, 2020 at 09:03AM

没有评论:

发表评论