c - Accessing pointers in a pointer to a union -


so have structure containing union follows:

struct fill{   char *name;   int id; };  struct test{   union{     struct fill *fill;     int type;   } *uni; }; 

i don't understand how access union members within structure. i've been trying follows:

struct test *test_struct, *test_int;  test_struct = malloc(sizeof(struct test)); test_struct->uni = malloc(sizeof(struct test)); test_struct->uni->fill->name = null; test->struct->uni->fill->id = 5;  test_int = malloc(sizeof(int)); test_int->uni->type = 10; 

but segfaults when try this. accessing these wrong? how should otherwise?

edit: sorry focusing on formatting , screwed declaration test. been fixed.

each of pointer members of struct must initialized, either allocate dynamic storage malloc, or assign other variables. here problems of code:

struct test *test_struct, *test_int;  test_struct = malloc(sizeof(struct test)); test_struct->uni = malloc(sizeof(struct test)); // uni should allocated size of union, not struct test_struct->uni->fill->name = null; // uni->fill pointer struct fill, should allocated before accessing members test->struct->uni->fill->id = 5;  test_int = malloc(sizeof(int)); // test_int of type struct test, allocating integer here test_int->uni->type = 10; // same, uni not allocated 

so try following fix:

struct test *test_struct, *test_int;  test_struct = malloc(sizeof(struct test)); test_struct->uni = malloc(sizeof(*test_struct->uni));         test_struct->uni->fill = malloc(sizeof(struct fill)); test_struct->uni->fill->name = null; test_struct->uni->fill->id = 5;  test_int = malloc(sizeof(struct test)); test_int->uni = malloc(sizeof(*test_struct->uni)); 

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -