【发布时间】:2015-06-27 21:09:19
【问题描述】:
我有这些结构:
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 函数输出。
这样做的正确方法是什么?
【问题讨论】:
标签: c pointers structure allocation unions