accessing initial common structure members
Richard Tobin
richard at aiai.ed.ac.uk
Tue Oct 23 04:39:28 AEST 1990
In article <1990Oct21.051028.11018 at zoo.toronto.edu> henry at zoo.toronto.edu (Henry Spencer) writes:
> It is dubious practice at best.
This technique is often used where an object may be of several different
kinds, with a type field to distinguish them. For example:
enum type {number, cons};
struct number {enum type type; int value;};
struct cons {enum type type; union obj *car, *cdr;};
union obj {struct number; struct cons;};
An alternative, of course, is to do it like this:
struct number {double value;};
struct cons {struct obj *car, *cdr;};
struct obj {enum type type;
union {struct cons cons; struct number number;} value;};
But if you want to allocate only the necessary amount of space when
creating a "number" object, the first form is simpler (you allocate
sizeof(struct number) and cast its address to a (union obj *), whereas
with the second form I think you would have to use something like
offsetof(struct obj, value) + sizeof(struct number)).
I would be interested to hear of elegant, portable ways to do this.
-- Richard
--
Richard Tobin, JANET: R.Tobin at uk.ac.ed
AI Applications Institute, ARPA: R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University. UUCP: ...!ukc!ed.ac.uk!R.Tobin
More information about the Comp.lang.c
mailing list