Path: utzoo!attcan!uunet!mcsun!ukc!edcastle!aiai!richard From: richard@aiai.ed.ac.uk (Richard Tobin) Newsgroups: comp.lang.c Subject: Re: accessing initial common structure members Message-ID: <3599@skye.ed.ac.uk> Date: 22 Oct 90 18:39:28 GMT References: <31468@netnews.upenn.edu> <1990Oct21.051028.11018@zoo.toronto.edu> Reply-To: richard@aiai.UUCP (Richard Tobin) Organization: AIAI, University of Edinburgh, Scotland Lines: 34 In article <1990Oct21.051028.11018@zoo.toronto.edu> henry@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@uk.ac.ed AI Applications Institute, ARPA: R.Tobin%uk.ac.ed@nsfnet-relay.ac.uk Edinburgh University. UUCP: ...!ukc!ed.ac.uk!R.Tobin