C 如何为结构中的指针数组分配内存?
我有以下结构:C 如何为结构中的指针数组分配内存?,c,pointers,structure,allocation,unions,C,Pointers,Structure,Allocation,Unions,我有以下结构: 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
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;
};
我不断出现分段错误,因为我在创建类型为taged\u 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\u generic\u attribute
返回指向generic\u attribute
对象的指针。我希望ta_ptr->attribute->generic
包含一个指向generic_attribute
对象的指针。指向generic\u属性
对象的指针由construct\u generic\u属性
函数输出
正确的方法是什么?您还需要为
属性成员分配空间
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;
};
因此,可以将union值设置为
ta_ptr->attribute.generic = construct_generic_attribute(args[0]);
非常感谢!我什么都有,除了。。。所以我将两个不同指针合并的原因是。。。我有泛型属性和复杂属性的构造函数,它们输出指针,以避免在内存中复制整个对象。因此,construct_generic_属性创建一个属性并为其分配空间。然后,它输出一个指针,以便不输出整个对象。然后,ta_ptr->attribute->generic被分配给该指针,而不是该对象。如果我按照你说的做,ta_ptr->attribute.generic=construct_generic_attribute。。。。然后,construct_generic_属性必须输出一个对象。对吗?(抱歉,我可能误解了)@RebeccaK375不是对象,因为c中不存在该概念,但您必须返回结构的副本。