簡體   English   中英

如何為結構中的指針數組分配內存?

[英]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返回一個指向generic_attribute對象的指針。 我希望ta_ptr->attribute->generic包含一個指向generic_attribute對象的指針。 這個指向generic_attribute對象的指針由construct_generic_attribute函數輸出。

這樣做的正確方法是什么?

您還需要為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()然后重新分配指針,實際上您的聯合不應該有指針,因為那樣它根本沒有任何作用,它是一個union ,其中兩個成員都是指針。

這會更有意義

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

所以你會像這樣設置聯合值

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM