-
nested structure help
Hello,
I have a structure that I would like to reference different structures using the same member. for example:
typedef struct
{
word32 menuItemEnabledFlag : 1;
word32 updateImmediatelyFlag : 1;
word32 absolutePositionFlag : 1;
word32 octorectFlag : 1;
word32 verticalTextFlag : 1;
word32 TimeoutFlag : 1;
word32 spare : 26; //spare bits
byte backgroundColor;
byte foregroundColor;
byte borderColor;
word16 xLeftPos;
word16 yTopPos;
word16 minXLength;
word16 minYLength;
byte displayField;
word32* field;
}tMENU_ITEM;
typedef struct
{
word32* firstGraphic;
word32* lastGraphic;
word32* current;
byte size;
}tGRAPHIC_FIELD;
tGRAPHIC_FIELD graphic;
typedef struct
{
word16 lowLimit;
word16 highLimit;
word16 current;
}tNUMERIC_FIELD;
tNUMERIC_FIELD numeric;
I would like the word32* field pointer to point to either a tGRAPHIC_FIELD structure or a tNUMERIC_FIELD structure, optionally. When I initialize the field member I use either:
(word32*) &graphic,
or
(word32*) &numeric,
If I want to access a member (like current, for example) of the tGRAPHIC_FIELD structure I can use a cast, like so, to get access to the member:
(mItem is a pointer to a instance of tMENU_ITEM)
fieldPtr = (*(tGRAPHIC_FIELD*)mItem->field).current;
The problem is this, I need a generic accessor to the nested structure and thus the cast is causing a problem. How can I get around this? Thanks. Please note that the "sub" structures are numerous and conditional statements wouldn't work.
-
Well if you want a cast-less solution, you need to do this
Code:
typedef struct
{
word16 lowLimit;
word16 highLimit;
word16 current;
} tNUMERIC_FIELD;
typedef struct
{
word32* firstGraphic;
word32* lastGraphic;
word32* current;
byte size;
} tGRAPHIC_FIELD;
typedef struct
{
// etc
byte displayField;
union {
tGRAPHIC_FIELD *gf;
tNUMERIC_FIELD *nf;
} field;
}tMENU_ITEM;
tGRAPHIC_FIELD graphic;
tNUMERIC_FIELD numeric;
Then you can do things like
Code:
tMENU_ITEM thing;
thing.field.gf = &graphic;
thing.field.gf->size = 23;
> I need a generic accessor to the nested structure
Your only other choice is to make field a void* type, but then you have to cast.