访问指向联合的指针中的指针

Accessing pointers in a pointer to a union

所以我有一个包含联合的结构,如下所示:

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

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

我不明白如何访问结构中的联合成员。我一直在尝试按如下方式进行:

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;

但是当我尝试这个时我遇到了段错误。我访问这些错误吗?不然怎么办?

编辑:抱歉,我专注于格式化,搞砸了 TEST 的声明。已修复。

结构的每个指针成员都必须初始化,可以通过 malloc 分配动态存储,也可以分配给其他变量。以下是您的代码的问题:

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

所以请尝试以下修复:

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