簡體   English   中英

結構內部的int數組

[英]int array inside a struct inside a struct

我正在嘗試實現這一目標...一個包含一個結構數組的容器,並且在每個結構內部都是一個int數組,它表示一個整數,如下所示... 12,345將位於int array [5] = { 1,2,3,4,5}

這是可以實現的一種方式。 我這種實現方式的主要問題是,我迷失了指向所有地方的所有指針,並且開始遍地都是垃圾數據,遍歷了段錯誤。 哦,對了,一切都是動態的。 好吧,幾乎所有我想的東西,如果您有一個struct容器,里面有一個結構,如果容器是malloc'd的,那么它里面的結構也是自動malloc'的,所以我的猜測是

容器-> struct.array

不確定????

您需要編寫自己的struct的malloc和free函數,並自己修改容器,並在需要容器或釋放其空間時每次調用它們,例如:

struct outside{
    struct inside *in;
};


struct inside{
    int *array;
};

struct outside *malloc_outside(size_t n) {
    int i;
    struct outside *o;
    o = (struct outside *)malloc(n*sizeof(struct outside));
    for(i=0;i<n;i++) {
        o->in = malloc(sizeof(struct inside));
        o->in->array = NULL;
    }
    return o;
}


void free_outside(struct outside *out) {
    free(out->in->array);
    free(out->in);
    free(out);
    return;
}

和malloc()數組的空間為malloc_outside()之后所需的空間

在C ++中,構造函數和析構函數更容易實現。

包含一個包含整數數組的結構數組的struct。 你問沒有指針

#define SIZE (8)

typedef struct {
    struct data {
        int idata[SIZE];
    };
    struct data arr[SIZE];
}record;

//or
struct data {
    int idata[SIZE];
};

typedef struct data arr[SIZE];

我不確定我是否已完全理解,但請看以下代碼:

struct MyStruct {
    int *array;
};
struct Container {
    struct MyStruct *array;
};

分配部分將是:

struct Container c;
c.array = malloc(sizeof(struct MyStruct) * NUM_STRUCTS);

for (i = 0; i < NUM_STRUCTS; ++i) {
    c.array[i].array = malloc(get_num_of_digits(12.345) * sizeof(int));    
}

我沒有測試此代碼,但應該完成此工作:P。 祝好運。

暫無
暫無

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

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