Home > database >  Declaring object classes in C?
Declaring object classes in C?

Time:02-05

I declared a few geometric figures types such as:

typedef struct s_sphere{
    t_tuple origin;
    double  radius;
} t_sphere;

typedef struct s_cylinder{
    t_tuple origin;
    double  height;
    double  radius;
} t_cylinder;

typedef struct s_triangle{
    t_tuple A;
    t_tuple B;
    t_tuple C;
} t_triangle;

etc...

Now, I would like to declare an intersection type which will contain two doubles and a geometric figure. I will then store all my intersections in a chained list:

// I do not know what type to give to geometric_figure
typedef struct  s_intersection{
    double       t1;
    double       t2;
//  what_type    geometric_figure;
} t_intersection;

typedef struct  s_intersection_list{
    t_intersection              intersection;
    struct s_intersection_list  *next;
} t_intersection_list;

I could use void* geometric_figure but I would like to avoid the most mallocs possible.
Is there a handy way of getting where I want without allocating geometric_object ?

CodePudding user response:

type which will contain two doubles and a geometric figure.

Consider union with an identifier.

typedef struct  s_intersection{
  double       t1;
  double       t2;
  int id;  // some id to know what type follows
  union {
    t_sphere sph;
    t_cylinder cyl;
    t_triangle tri;
  } u;
} t_intersection;

If t_intersection is to be allocated, consider a flexible member array to right size the allocation.

typedef struct  s_intersection{
  double       t1;
  double       t2;
  int id;  // some id to know what type follows
  union {
    t_sphere sph;
    t_cylinder cyl;
    t_triangle tri;
  } u[];   // FAM
} t_intersection;

Example: allocate a triangle.

t_intersection *p = malloc(sizeof *p   sizeof p->u[0].tri);
  • Related