这是我声明的类型:(
我也t_sphere声明了)t_cylindert_triangle
typedef struct s_intersection{
double t1;
double t2;
int id;
union {
t_sphere sph;
t_cylinder cyl;
t_triangle tri;
} u[];
} t_intersection;
Run Code Online (Sandbox Code Playgroud)
要引用结构体中的联合变量,我必须提前知道它是什么类型。这是可能的,这要归功于我的结构中声明的 id int,但是用我想到的方法来实现它是非常繁重的。
这是我编写的用于分配 t_intersection 变量的函数:
t_intersection *intersection(unsigned int geometric_figure_id, void *figure)
{
t_intersection *p;
if (geometric_figure_id == SPHERE_ID)
p = malloc(sizeof(*p) + sizeof (p->u[0].sp));
else if (geometric_figure_id == CYLINDER_ID)
p = malloc(sizeof(*p) + sizeof (p->u[0].cy));
else if (geometric_figure_id == TRIANGLE_ID)
p = malloc(sizeof(*p) + sizeof (p->u[0].tr));
if (p == NULL)
return (NULL); …Run Code Online (Sandbox Code Playgroud) 我总是被告知,只要我可以在没有内存的情况下实现完全相同的事情,就不要分配内存。
人们是否这么说是因为释放代码中的内容可能需要一些时间,还是有一个以效率为导向的解释?(例如更好的性能)