(Really addressing inside struct)Re: get size of malloc'd object

Joseph S. D. Yao jsdy at hadron.UUCP
Thu Jul 24 15:09:55 AEST 1986


In article <403 at anasazi.UUCP> john at anasazi.UUCP (John Moore) writes:
>We have a structure with a number of structures contained within it. 
>Because of linked list processing, we have a pointer to one of the
>structures within, and we want to derive a pointer to the top of
>the structure without LINT complaining, and in a truly portable way.
>struct links {
>   struct links *forward;
>   struct links *backward;
>};
>struct foo {
>   char bar;
>   struct links snake;
>   struct whocares junk;
>   struct links lizard;
>};
	Assume struct foo ssssss;
>struct links *reptile = &ssssss.lizard;
>struct foo *iwish = (mystery function of reptile);
>Example of a wrong solution:
>struct foo *iwish = (struct foo *)((char *)reptile + (char *)0->lizard);

You can't add pointers.

There really isn't a very good and portable solution in C.  Given
your constraints, the best is to replace "+ (char *)0->lizard" with:
"- ((int)(((char *)&ssssss.lizard) - ((char *)&ssssss)))"; and even
this is not guaranteed.  What you need to do is expand your mental
model somewhat.  Assuming that links are always inside foos (to
get out of the necessity of using unions):

struct links {
	struct foo *forward;
	struct foo *backward;
};

Replace mystery-function with identity.
Replace ->forward with ->forward->lizard or ->forward->snake, as
appropriate.  You may find yourself realizing a better yet way to
express yourself, and say what you mean (instead of what you thought
you wanted to cleverly express).
-- 

	Joe Yao		hadron!jsdy at seismo.{CSS.GOV,ARPA,UUCP}
			jsdy at hadron.COM (not yet domainised)



More information about the Comp.lang.c mailing list