How do I access elements in this stuct if I initialize a list as follows:
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;
I tried using (*list)->id = 'A' and it compiles but then gets a segmentation fault error when running the program.
Although it compiles fine, you didn’t allocate memory correctly.
You allocated memory for
group **list, which is eventually an array of pointers to structgroup. What I think you intended to do doing is:Now for each pointer in the array, allocate its own memory:
For instance, to access
idin the 2nd struct, you do:Note that
*listaccess the first struct, and is equivalent tolist[0].Sidenote:
Two levels of indirection allow you to store the structs in a non-continuous way in the memory. Alternatively, you can use one level of indirection and store them continuously:
and then access the members with: