释放结构中的结构数组

Hyn*_*ard 1 c memory arrays free struct

我有两个结构

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

struct cluster_t {
    int size;
    int capacity;
    struct obj_t *obj;
};
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,有指向第一obj_t内部cluster_t

我想要做的是从 cluster_t 内的数组中释放每个 obj_t

我必须用这样的for循环来写吗?

void clear_cluster(struct cluster_t *c)
{
    for(int i = 0; i<c->size;i++)
    {
        free(&c->obj[i]);
    }
    free(c->obj);
}
Run Code Online (Sandbox Code Playgroud)

或者像这样释放内存可以吗?

void clear_cluster(struct cluster_t *c)
{
    free(c->obj);
}
Run Code Online (Sandbox Code Playgroud)

e0k*_*e0k 5

你所拥有的free()每一个都应该有一个malloc(),并以与分配它相反的顺序执行。

领域objcluster_t是一个指针数组object_t。这可能malloc()在初始化您的cluster_t(类似于c->obj = malloc(c->capacity*sizeof(*c->obj)))时分配了一个,因此只需调用一次即可释放它free()。然后你会想要释放cluster_t分配本身(假设它也是动态分配的):

free(c->obj);
free(c);
Run Code Online (Sandbox Code Playgroud)

然而,如果每个 object_t本身都有动态分配,就会有区别。(在您的示例中,object_t没有。)在这种情况下,您将需要malloc()在创建数组时遍历数组和分配,因此free()在最后执行相反的操作和每个。