简体   繁体   English

C-访问结构中的动态数组

[英]C - accessing dynamic array within a struct

I'm trying to create cluster with dynamic array objects. 我正在尝试使用动态数组对象创建集群。

Struct definitions are following: 结构定义如下:

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

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

Function for adding object to cluster is: 向集群添加对象的功能是:

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++;
}

EDIT: Here is resize_cluster() function: 编辑:这是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;
}

EDIT 2: Here is cluster initialization: 编辑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));
}

I can't figure out why program crashes when I try to add the object to the array in cluster. 我无法弄清楚为什么在尝试将对象添加到群集中的数组时程序崩溃。 Is accessing array this way wrong? 这样访问数组是错误的吗? If so, how should I access it? 如果是这样,我应该如何访问它?

The issue is the call to init_cluster() . 问题是对init_cluster()的调用。 The c parameter is passed-by-value, so whatever you are sending remains unmodified: c参数是按值传递的,因此您发送的任何内容均保持不变:

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

One fix would be to pass a pointer to an object: 一种解决方法是将指针传递给对象:

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

Then remove c = malloc(sizeof(struct cluster_t)); 然后删除c = malloc(sizeof(struct cluster_t)); from init_cluster() ; 来自init_cluster() ;

Or, you could create an alloc_cluster function: 或者,您可以创建一个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;
}

And call it like: 并这样称呼:

struct cluster_t *c = init_cluster(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM