[英]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. 编辑:对不起,我专注于格式设置,我搞砸了TEST声明。 Its been fixed. 它是固定的。
Each of the pointer members of the struct must be initialized, either by allocate dynamic storage by malloc
, or assign to other variables. 必须通过malloc
分配动态存储或将其分配给其他变量来初始化该结构的每个指针成员。 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.