address of structure == address of first member?

Chris Torek chris at mimsy.UUCP
Sun Nov 27 09:35:51 AEST 1988


[Amazing that no one else has jumped on this yet.]
>In article <2176 at iscuva.ISCS.COM> carlp at iscuva.ISCS.COM (Carl Paukstis) writes:
>>86	        code = strcmp (key, *(char **)((char *)table + (m * size)));
[much edited]

In article <8976 at smoke.BRL.MIL> gwyn at smoke.BRL.MIL (Doug Gwyn) suggests:
>You already had a (char *).  You then cast it to (char **), and then
>dereferenced that using the * operator.  There was no need for these
>extra steps when the original (char *) was just what you needed.

But the original `char *' is not what he needs, and this does not compile
into an effective no-op (as you suggested in <8954 at smoke.brl.mil>).  If
we write:

	char *p;
	
	p = (char *)table + (m * size);

we have p pointing at (not `to': I am reserving that for a pointer of
the appropriate type) an object of `struct <something>'.  This structure
is defined as:

	struct <something> {
		char	*name;
		...
	};

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.

	struct name { char *name; };

	result = strcmp(key, ((struct name *)p)->name);

or

	result = strcmp(key, *(char **)p);

The former is in some sense superiour, particularly under K&R rules,
where any pair of structures that have an initial common set of names
and types are, in that common part, compatible.  (This rule is left
over from the days before unions, and does not appear in the dpANS.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list