簡體   English   中英

C-訪問結構中的動態數組

[英]C - accessing dynamic array within a struct

我正在嘗試使用動態數組對象創建集群。

結構定義如下:

struct obj_t {
    int id;
    float x;
    float y;
};

struct cluster_t {
    int size;
    int capacity;
    struct obj_t *obj;
};

向集群添加對象的功能是:

void append_cluster(struct cluster_t *c, struct obj_t obj)
{
    if(c->capacity < (c->size + 1))
    {
        c = resize_cluster(c, c->size + 1);
    }
    if(c == NULL)
        return;
    c->obj[c->size] = obj;    //at this point program crashes.
    c->size++;
}

編輯:這是resize_cluster()函數:

struct cluster_t *resize_cluster(struct cluster_t *c, int new_cap)
{
    if (c->capacity >= new_cap)
        return c;

    size_t size = sizeof(struct obj_t) * new_cap;

    void *arr = realloc(c->obj, size);
    if (arr == NULL)
        return NULL;

    c->obj = (struct obj_t*)arr;
    c->capacity = new_cap;
    return c;
}

編輯2:這是群集初始化:

void init_cluster(struct cluster_t *c, int cap)
{
    c = malloc(sizeof(struct cluster_t));
    c->size = 0;
    c->capacity = cap;
    c->obj = (struct obj_t*)malloc(cap * sizeof(struct obj_t));
}

我無法弄清楚為什么在嘗試將對象添加到群集中的數組時程序崩潰。 這樣訪問數組是錯誤的嗎? 如果是這樣,我應該如何訪問它?

問題是對init_cluster()的調用。 c參數是按值傳遞的,因此您發送的任何內容均保持不變:

struct cluster_t * c;
init_cluster(c, 1);
// c is uninitialized!

一種解決方法是將指針傳遞給對象:

struct cluster_t c;
init_cluster(&c, 1);

然后刪除c = malloc(sizeof(struct cluster_t)); 來自init_cluster() ;

或者,您可以創建一個alloc_cluster函數:

struct cluster_t * alloc_cluster(int cap)
{
    c = malloc(sizeof(struct cluster_t));
    c->size = 0;
    c->capacity = cap;
    c->obj = malloc(cap * sizeof(struct obj_t));
    return c;
}

並這樣稱呼:

struct cluster_t *c = init_cluster(1);

暫無
暫無

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

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