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中不存在,但是你必须返回一个结构体的副本。 –