c - 访问指向 union 的指针中的指针

标签 c pointers struct unions

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

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

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

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

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

关于c - 访问指向 union 的指针中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831325/

相关文章:

c - 'C' - 如何用 32 位浮点值初始化 32 位整数值?

while 循环中的逗号运算符

c - 同时启动 pthreads

c++ - 为什么++(* p)更改指针值?

接收指向结构的二维数组的指针的 C 函数

c - 从单行读取多个数据

c - c中的int(*pt)[5]是什么意思

c++ - 在类方法上使用指针 : Expression must have type bool error

c - 为什么共享内存中的 memcpy 会出现段错误

类中的c++动态结构