2015-06-27 135 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中不存在,但是你必須返回一個結構體的副本。 –