-1

I have a struct that contain an attribute that can take many types, I want ask about the most appropriate way to declare this attribute.

Example:

struct 
{
void* pShape; //poiter to the shape that will be casted on *tCircle or *tRectangle
int type;//type of the shape
int h;
int l;
}tImage;

struct{
int size;
int r;
HANDLE calcul;
}tCircle

struct{
int size;
int x;
int y;
HANDLE calcul;
}tRectangle;

As you see here i'am using void* to declare a pointer to the shape and use type attribute to guess the type of the shape.

this is my function for the calcuation of the size of the shape in an image

int Image_Get_ShapeSize(tImage Im)
{
 switch (Im.type)
 {
 case CIRCLE:
 ((tCircle*)(Im.shape))->calcul();
 break;

 case RECTANGLE:
 ((tRectangle*)(Im.shape))->calcul();
 break;

 default:
 break;
}
}

what do you think about this is it a good method ?

fedi
  • 368
  • 3
  • 7
  • 18
  • How is `HANDLE` defined? – sjsam May 04 '16 at 07:59
  • I'd suggest creating specific functions for all the shapes. – bzeaman May 04 '16 at 08:04
  • Possible duplicate of [C struct to void\* pointer](http://stackoverflow.com/questions/10319080/c-struct-to-void-pointer) –  May 04 '16 at 08:23
  • @bzeaman yes, indeed, in the initialization of a variable of type tCircle or tRectangle the attribute calcul wil point on different functions – fedi May 04 '16 at 09:18

1 Answers1

1

I do not understand well why you need the tCircle and tRectangle structures because they have the same fields. I suggest you use only one definition and initialize the function pointer to a different and specific method.

struct shape {
    int size;
    int x;
    int y;

    void (*calcul) (struct shape * shape);
};

And then the specific functions:

void circle_calcul(struct shape * shape)
{
    ...
}

void rectangle_calcul(struct shape * shape)
{
    ...
}

And finally:

struct shape circle;
struct shape rectangle;

circle.calcul = circle_calcul;
rectangle.calcul = rectangle_calcul;
klyone
  • 94
  • 1
  • 10