释放结构内的结构数组
Freeing array of structs inside struct
我有两个结构
struct obj_t {
int id;
float x;
float y;
};
struct cluster_t {
int size;
int capacity;
struct obj_t *obj;
};
如你所见,cluster_t
里面有指向第一个obj_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);
}
或者像这样释放内存可以吗?
void clear_cluster(struct cluster_t *c)
{
free(c->obj);
}
要看你怎么分配了。看来你做了类似
的事情
struct cluster_t cluster;
cluster.obj = malloc(sizeof (struct obj_t) * SOMENUMBER);
在这种情况下,cluster.obj
只是一个指向数组的指针。您只需
free(cluster.obj)
或
free(c->obj)
在接收指向 c
的指针的函数中。
如果你有一个指针数组,你只需要遍历调用 free
的数组。
记住&
取变量的内存地址。您不释放指针,而是释放指针指向的内存。你永远不会做像 free(&pointer)
.
这样的事情
每个 malloc()
应该有一个 free()
,并按照与分配顺序相反的顺序执行。
cluster_t
的字段obj
是指向object_t
数组的指针。这可能是在初始化您的 cluster_t
时分配的 malloc()
(类似于 c->obj = malloc(c->capacity*sizeof(*c->obj))
),因此只需调用一次 free()
即可释放它。然后你会想要释放 cluster_t
分配本身(假设它也是动态分配的):
free(c->obj);
free(c);
但是,如果 each object_t
本身有一个动态分配,就会有所不同。 (在您的示例中, object_t
没有。)在这种情况下,您需要在创建数组时遍历数组和 malloc()
分配,因此执行相反的操作 free()
每个都在最后。
我有两个结构
struct obj_t {
int id;
float x;
float y;
};
struct cluster_t {
int size;
int capacity;
struct obj_t *obj;
};
如你所见,cluster_t
obj_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);
}
或者像这样释放内存可以吗?
void clear_cluster(struct cluster_t *c)
{
free(c->obj);
}
要看你怎么分配了。看来你做了类似
的事情struct cluster_t cluster;
cluster.obj = malloc(sizeof (struct obj_t) * SOMENUMBER);
在这种情况下,cluster.obj
只是一个指向数组的指针。您只需
free(cluster.obj)
或
free(c->obj)
在接收指向 c
的指针的函数中。
如果你有一个指针数组,你只需要遍历调用 free
的数组。
记住&
取变量的内存地址。您不释放指针,而是释放指针指向的内存。你永远不会做像 free(&pointer)
.
每个 malloc()
应该有一个 free()
,并按照与分配顺序相反的顺序执行。
cluster_t
的字段obj
是指向object_t
数组的指针。这可能是在初始化您的 cluster_t
时分配的 malloc()
(类似于 c->obj = malloc(c->capacity*sizeof(*c->obj))
),因此只需调用一次 free()
即可释放它。然后你会想要释放 cluster_t
分配本身(假设它也是动态分配的):
free(c->obj);
free(c);
但是,如果 each object_t
本身有一个动态分配,就会有所不同。 (在您的示例中, object_t
没有。)在这种情况下,您需要在创建数组时遍历数组和 malloc()
分配,因此执行相反的操作 free()
每个都在最后。