C - using union, memory allocation

I have a C structure that looks like this:

typedef struct event_queue{ Event* event; int size; int front; int count; int delay; } event_queue; 

This is the main roundabout. The value of the event is an array of EventPointers, and it traversed each time X to remove the event from one of the events. It was initialized as

 p->event = calloc(p->size, sizeof(Event)); 

Thing is, I want to make a similar queue, with similar functionality, for a queue of other types of similar events, but with slightly different data. Initially, I just wanted to have separate queues and go through them separately, but the functionality repeats this way, it seems like I'm just doing it wrong. Imagine that the "sister" queue is exactly the same, but with a pointer to a different type for the "event".

Should I use a union for this? such as

 typedef struct event_queue{ union{ Event* event; VisualEvent* visual; } data; unsigned char* datatype; //array of same size as data for every individual member int size; int front; int count; int delay; } event_queue; 

But in this case, how do I allocate memory for an array? Should I keep them separate and is this a bad idea?

+2
source share
1 answer

One solution is to create the base event type of a union , possibly tagged:

 enum EEventType { TypeOne, TypeTwo }; typedef struct EventTag_ { EEventType tag; } EventTag; typedef struct EventOne_ { EEventType tag; // real data for this event type; } EventOne; typedef struct EventTwo_ { EEventType tag; // real data for the sister event type; } EventTwo; typedef union Event_ { EventTag kind; EventOne event1; EventTwo event2; } Event; 

Now create an array of Event s. For each Event * p you can check e->kind.tag no matter which union member is active at that moment (thanks to a special rule regarding the initial sequences of struct union members).

+3
source

Source: https://habr.com/ru/post/1240232/


All Articles