Path: utzoo!utgpu!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!rutgers!cmcl2!adm!smoke!gwyn From: gwyn@smoke.BRL.MIL (Doug Gwyn ) Newsgroups: comp.lang.c Subject: Re: address of structure == address of first member? Message-ID: <8987@smoke.BRL.MIL> Date: 27 Nov 88 12:03:50 GMT References: <2172@iscuva.ISCS.COM> <8954@smoke.BRL.MIL> <2176@iscuva.ISCS.COM> <8976@smoke.BRL.MIL> <14725@mimsy.UUCP> Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 40 In article <14725@mimsy.UUCP> chris@mimsy.UUCP (Chris Torek) writes: >To be completely type-correct, we should convert `p' into a pointer to >the correct structure type-name, and follow that to its `name' field. >The problem, of course, is that in this general-purpose search routine, >we have no idea *which* structure `p' is standing for [to end the >sentence a preposition with]. There are two alternatives: define a >structure that contains only a name; or cheat. Technically it is not necessary to do this via a purely "type correct" method; there are sufficient requirements imposed by the very latest proposed C standard to ensure that any addressable data object forms a linear address subspace within itself, such that (char *)-arithmetic suffices to correctly address its pieces. This guarantee was necessary to make memcpy() etc. usable for their intended purposes. Cheating is guaranteed to suffice. A pointer to a structure converted to (char *) must compare equal to a pointer to the first member of the structure converted to (char *), and in this particular example casting that back to (char **) will produce a valid pointer to the first structure whose type is (char *). Then * will pick up the contents of that (char *) for use with strcmp(). (I made a mistake about this in my previous posting. strcmp() does need the (char *) itself, not just its address, so the additional *(char**) is necessary. Sorry.) I admit to being surprised fairly recently when I found that this "cheating" was supposed to be officially sanctioned, but it's useful. The wording about "same representation and alignment" was also fixed so that one can safely pass a nonnegative int to a function expecting an unsigned int, or a non-qualified type to a function with parameter declared as a qualified version of that type, etc. This (along with a fix to the definition for fprintf() %u format) seems to complete the work of making C object representations behave as usefully as possible without undue burden for implementors on segmented, ones- complement, etc. architectures. A further nice thing is that the K&R 2nd Ed. example where a pointer to a function of a slightly different type than expected was passed (for a sorting comparison function, I think) is now guaranteed to actually work the way K&R used it. This had been bothering me..