C - 使用联合,分配内存
我有一个 C 结构,看起来像这样
typedef struct event_queue{
Event* event;
int size;
int front;
int count;
int delay;
} event_queue;
这是一个基本的循环队列。事件值是一个 EventPointers 数组,每 X 次都会遍历一次以使其中一个事件出列。 它的初始化就像
p->event = calloc(p->size, sizeof(Event));
事情一样,我想做一个类似的队列,具有类似的功能,以对其他类型的类似事件进行排队,但数据略有不同。最初我只是想拥有单独的队列并分别遍历它们,但是功能如此重复,看起来我只是做错了。 想象一下“姐妹”队列是完全相同的,但具有指向“事件”的不同类型的指针。
我应该使用联合来代替吗?比如
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;
但是那样的话,我该如何为数组分配内存呢?我应该把它们分开吗?这是一个坏主意吗?
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;
It's a basic circular queue. The event value is an array of EventPointers, and it's traversed every X time to dequeue one of the events.
It's initialized like
p->event = calloc(p->size, sizeof(Event));
Thing is, I want to do a similar queue, with similar functionality, to queue other type of similar events but with slightly different data. Initially I just wanted to have separate queues and traverse them separately, but the functionality is so repeated, it seems like I am just doing it wrong.
Imagine the "sister" queue as being exactly the same, but with a pointer to a different type for "event".
Should I use an union for this instead? 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 that case, how do I allocate memory for the array? Should I keep them separate, and this is a bad idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种解决方案是使基本事件类型成为一个
联合
,也许是一个标记的事件类型:现在创建一个
Event
数组。对于每个Event * p
,您都可以检查e->kind.tag
,无论当时哪个联合成员处于活动状态(这要归功于有关初始序列的特殊规则)结构体工会成员)。One solution is to make the basic event type a
union
, perhaps a tagged one:Now make an array of
Event
s. For everyEvent * p
, you can inspecte->kind.tag
no matter which union member is active at that moment (thanks to a special rule concerning initial sequences of struct union members).