如何为结构中的指针数组分配内存?

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 returns 指向 generic_attribute 对象的指针。我希望 ta_ptr->attribute->generic 包含指向 generic_attribute 对象的指针。 generic_attribute 对象的指针由 construct_generic_attribute 函数输出。

执行此操作的正确方法是什么?

您也需要为 attribute 成员分配 space。

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]);