C - Using an union, allocating memory

限于喜欢 提交于 2019-12-06 09:03:18

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;

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).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!