gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:07 24 4
gpt4 key购买 nike

所以我有一个包含 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com