[英]How to allocate memory for an array of pointers within a structure?
我有這些結構:
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
函數輸出。
這樣做的正確方法是什么?
您還需要為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()
然后重新分配指針,實際上您的聯合不應該有指針,因為那樣它根本沒有任何作用,它是一個union
,其中兩個成員都是指針。
這會更有意義
union union_attribute {
struct complex_attribute complex;
struct generic_attribute generic;
};
所以你會像這樣設置聯合值
ta_ptr->attribute.generic = construct_generic_attribute(args[0]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.