On Nov 21, 6:13*am, "Guillaume Dargaud"
<use_the_form_on_my_contact_p...@www.gdargaud.netw rote:
Hello all,
I wonder if there's a way to obtain a given field from different structs.
Something like this:
struct sDigital {
*char Label[255];
*int Something;
} tDigital;
struct sAnalog {
*double SomethingElse;
*char Label[255];
} tAnalog;
char *GetLabel(void* DigOrAnal) {
* * return DigOrAnal->Label;
}
I know that doesn't work and I have to add a type variable indicator and a
slew of 'if' tests. But I wonder if there are some simplifying tricks.
--
Guillaume Dargaudhttp://www.gdargaud.net/
Chris Dollin's suggestion is the right one; redesign your types so
that you have a single struct type with variant members for analog and
digital:
typedef struct sComm
{
char Label[255];
union {
tdigital digitalStuff;
tanalog analogStuff;
} digitalOrAnalog;
} tComm;
Having said that, here's one trick I've used in the past, and I think
it's applicable generally (but don't take my word for it). The
address of the first member of a struct object is the same as the
address of the struct object itself. You could rearrange your struct
definitions so that Label is the first member of both:
typedef struct sDigital
{
char Label[255];
...
} tDigital;
typedef struct sAnalog
{
char Label[255];
...
} tAnalog;
That way, a pointer to the struct can easily be cast into a pointer to
the Label buffer:
tDigital d;
char *dlabel = (char *) &d; // dlabel now points to d.Label
tAnalog a;
char *alabel = (char *) &a; // alabel now points to a.Label
Obviously, that's a bit ugly and non-intuitive, which is why you
should go with Chris' suggestion.