我有一个结构,它只包含指向我分配的内存的指针。有没有办法递归地释放作为指针的每个元素,而不是在每个元素上调用 free?
例如,假设我有这个布局:
typedef struct { ... } vertex;
typedef struct { ... } normal;
typedef struct { ... } texture_coord;
typedef struct
{
vertex* vertices;
normal* normals;
texture_coord* uv_coords;
int* quads;
int* triangles;
} model;
在我的代码中,我 malloc 每个结构来创建一个模型:
model* mdl = malloc (...);
mdl->vertices = malloc (...);
mdl->normals = malloc (...);
mdl->uv_coords = malloc (...);
mdl->quads = malloc (...);
mdl->triangles = malloc (...);
像这样释放每个指针很简单:
free (mdl->vertices);
free (mdl->normals);
free (mdl->uv_coords);
free (mdl->quads);
free (mdl->triangles);
free (mdl);
有没有一种方法可以递归地遍历 mdl 中的指针,而不是在每个元素上调用 free ?
(在实践中,只为每个编写 free() 几乎没有任何工作,但它会减少代码重复并有助于学习)