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
函數輸出。
什麼是做到這一點的正確方法?
非常感謝!我得到的一切除了...所以...我做了兩個不同指針的聯合的原因是...我有generic_attribute和complex_attribute輸出指針的構造函數,以避免整個對象被複制到內存中。所以construct_generic_attribute創建一個屬性併爲它分配空間。然後它輸出一個指針,以便不輸出整個對象。然後,將ta_ptr-> attribute-> generic分配給該指針,而不是該對象。 – RebeccaK375
如果我按照你所說的做了,ta_ptr-> attribute.generic = construct_generic_attribute ....然後construct_generic_attribute必須輸出一個對象。對? (對不起,我可能會誤解) – RebeccaK375
@ RebeccaK375不是一個對象,因爲這個概念在c中不存在,但是你必須返回一個結構體的副本。 –