2016-04-25 72 views
0

所以我有一个包含一个联合结构如下:的指针访问指针工会

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; 

但我得到segfaults,当我尝试这个。我访问这些错误吗?我应该怎么做呢?

编辑:对不起,我是专注于格式化和我搞砸了测试声明。它已被修复。

+3

如何提供'结构TEST'的完整,准确的申报?你提交的那个似乎被截断了。 –

+1

没有遗憾,是我犯的一个错误,我已经纠正了,但,这是完整的声明。 – Phenom588

+0

什么是'type'联盟内部的目的,如果你永远不会成为能够使用它?你应该把'type'放在struct中,其余的放在union中。 – 2501

回答

2

每个该结构的指针构件必须被初始化,或者通过由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)); 
+0

有什么问题?为什么下降? – fluter

+0

我不确定是谁做的?但那正是我所需要的,非常感谢你!看起来,我对工会有一种有趣的误解,我认为当我分配内存时,我将分配给我使用的任何工会成员,而工会则是该成员的大小。 – Phenom588