Ç - 使用工会,分配内存 [英] C - Using an union, allocating memory

查看:107
本文介绍了Ç - 使用工会,分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C结构,看起来像这样

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;

这是一个基本的循环队列。该事件值EventPointers数组,它的走过每X时间出列的事件之一。
它的初始化像

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?

推荐答案

解决方案之一是使基本事件键入联盟,也许是一个标记之一:

One solution is to make the basic event type a union, perhaps a tagged one:

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;

现在让事件组成的数组。对于每一个事件* P ,您可以检查 E-GT&; kind.tag 无论哪个联合成员是活动那一刻(感谢有关结构工会会员的初始序列的特殊规则)。

Now make an array of Events. For every Event * p, you can inspect e->kind.tag no matter which union member is active at that moment (thanks to a special rule concerning initial sequences of struct union members).

这篇关于Ç - 使用工会,分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆