Phenom588
Phenom588

Reputation: 81

Accessing pointers in a pointer to a union

So I have structure containing a union as follows:

struct FILL{
  char *name;
  int id;
};

struct TEST{
  union{
    struct FILL *fill;
    int type;
  } *uni;
};

I don't understand how to access the union members within the structure. I've been trying to do it as 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 I get segfaults when I try this. Am I accessing these wrong? How should I do it otherwise?

Edit: Sorry I was focusing on the formatting and I screwed up the declaration for TEST. Its been fixed.

Upvotes: 0

Views: 640

Answers (1)

fluter
fluter

Reputation: 13786

Each of the pointer members of the struct must be initialized, either by allocate dynamic storage by malloc, or assign to other variables. Here are the problems of your code:

struct TEST *test_struct, *test_int;

test_struct = malloc(sizeof(struct TEST));
test_struct->uni = malloc(sizeof(struct TEST)); // uni should be allocated with size of the union, not the struct
test_struct->uni->fill->name = NULL; // uni->fill is a pointer to struct FILL, it should be allocated too before accessing its members
test->struct->uni->fill->id = 5;

test_int = malloc(sizeof(int)); // test_int is of type struct TEST, you are allocating a integer here
test_int->uni->type = 10; // same, uni not allocated

So try the 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));

Upvotes: 4

Related Questions