2015-06-27 99 views
2

我有这些结构:如何为结构中的指针数组分配内存?

struct generic_attribute{ 
    int current_value; 
    int previous_value; 
}; 

union union_attribute{ 
    struct complex_attribute *complex; 
    struct generic_attribute *generic; 
}; 

struct tagged_attribute{ 
    enum{GENERIC_ATTRIBUTE, COMPLEX_ATTRIBUTE} code; 
    union union_attribute *attribute; 
}; 

我不断收到分段故障错误,因为创建tagged_attribute类型的对象的时候,我没有正确分配内存。

struct tagged_attribute* construct_tagged_attribute(int num_args, int *args){ 
    struct tagged_attribute *ta_ptr; 
    ta_ptr = malloc (sizeof(struct tagged_attribute)); 
    ta_ptr->code = GENERIC_ATTRIBUTE; 
    //the problem is here: 
    ta_ptr->attribute->generic = malloc (sizeof(struct generic_attribute)); 
    ta_ptr->attribute->generic = construct_generic_attribute(args[0]); 
    return ta_ptr; 
} 

construct_generic_attribute返回一个指向一个generic_attribute对象。我想要ta_ptr->attribute->generic包含一个指向generic_attribute对象的指针。这个指向generic_attribute对象的指针由construct_generic_attribute函数输出。

什么是做到这一点的正确方法?

回答

2

您还需要为attribute成员分配空间。

struct tagged_attribute* construct_tagged_attribute(int num_args, int *args) 
{ 
    struct tagged_attribute *ta_ptr; 
    ta_ptr = malloc(sizeof(struct tagged_attribute)); 
    if (ta_ptr == NULL) 
     return NULL; 
    ta_ptr->code = GENERIC_ATTRIBUTE; 
    ta_ptr->attribute = malloc(sizeof(*ta_ptr->attribute)); 
    if (ta_ptr->attribute == NULL) 
    { 
     free(ta_ptr); 
     return NULL; 
    } 
    /* ? ta_ptr->attribute->generic = ? construct_generic_attribute(args[0]); ? */ 
    /* not sure this is what you want */ 

    return ta_ptr; 
} 

,你不应该malloc()的属性,然后重新分配指针,其实你的工会不应该有poitner,因为那时它没有任何作用的话,那是一个union其中两个成员是指针。

这样会更有意义

union union_attribute { 
    struct complex_attribute complex; 
    struct generic_attribute generic; 
}; 

所以你会设置工会值一样

ta_ptr->attribute.generic = construct_generic_attribute(args[0]); 
+0

非常感谢!我得到的一切除了...所以...我做了两个不同指针的联合的原因是...我有generic_attribute和complex_attribute输出指针的构造函数,以避免整个对象被复制到内存中。所以construct_generic_attribute创建一个属性并为它分配空间。然后它输出一个指针,以便不输出整个对象。然后,将ta_ptr-> attribute-> generic分配给该指针,而不是该对象。 – RebeccaK375

+1

如果我按照你所说的做了,ta_ptr-> attribute.generic = construct_generic_attribute ....然后construct_generic_attribute必须输出一个对象。对? (对不起,我可能会误解) – RebeccaK375

+0

@ RebeccaK375不是一个对象,因为这个概念在c中不存在,但是你必须返回一个结构体的副本。 –