【问题标题】:How to allocate memory for an array of pointers within a structure?如何为结构中的指针数组分配内存?
【发布时间】: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


    【解决方案1】:

    您还需要为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() 然后重新分配指针,事实上你的联合不应该有 poitner,因为那样它根本没有任何用途,它是一个 union 两个成员都是指针.

    这样会更有意义

    union union_attribute {
        struct complex_attribute complex;
        struct generic_attribute generic;
    };
    

    所以你可以设置联合值

    ta_ptr->attribute.generic = construct_generic_attribute(args[0]);
    

    【讨论】:

    • 非常感谢!我得到了一切,除了......所以......我将两个不同的指针联合起来的原因是......我有generic_attribute和complex_attribute的构造函数,它们输出指针,以避免整个对象被复制到内存中。因此,construct_generic_attribute 创建一个属性并为其分配空间。然后它输出一个指针,以便不输出整个对象。然后,将 ta_ptr->attribute->generic 分配给该指针而不是该对象。
    • 如果我按照你说的做,ta_ptr->attribute.generic = construction_generic_attribute....那么construct_generic_attribute 必须输出一个对象。正确的? (对不起,我可能误会了)
    • @RebeccaK375 不是对象,因为该概念在 c 中不存在,但您必须返回结构的副本。
    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 2019-09-23
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2015-04-16
    • 2023-04-02
    相关资源
    最近更新 更多