Sha*_*les 1 c malloc struct pointers
如果我按如下方式初始化列表,如何访问此结构中的元素:
group **list = (group **) malloc(sizeof(group)); 
typedef struct
{
    // ID of the group, 'A' to 'D'
    char id;
    // a list of members in the group 
    char **members;
} group;
Run Code Online (Sandbox Code Playgroud)
我尝试使用(*list)->id = 'A'并编译,但在运行程序时出现分段错误错误.
struct group
{
    // ID of the group, 'A' to 'D'
    char id;
    // a list of members in the group 
    char **members;
};
//this initializes one group
group *a_group = malloc(sizeof(struct group)); //cast not needed in C
//this initializes an array of 10 group
group **list = malloc(sizeof(struct group *) * 10);
//initialize each one of the 10
for(int i = 0; i < 10; ++i){
  list[i] = malloc(sizeof(struct group));
}
//get something out of group
a_group->id;
//get first group out of list
list[0]->id;
*list->id;
// 10 elements continuous memory
group *array_of_groups = malloc(sizeof(struct group) * 10);
array_of_groups[0].id;
*array_of_groups.id;
Run Code Online (Sandbox Code Playgroud)