[comp.lang.c] pointer casts & malloc

greg@utcsri.UUCP (Gregory Smith) (12/09/86)

In article <427@viper.UUCP> dave@viper.UUCP (David Messer) writes:
>...and conversion to a pointer to a smaller
>type and back, which also results in the same original pointer value.

That is to say,
typedef foo (anything you want);
foo *foop;
	/* (foo *)(char *) foop == foop  is guaranteed */
	
Since a (char *) is being converted to a valid (foo *) here, there must
exist a subset of (char *)'s which can be converted to valid (foo *)'s.
This subset can be found by applying a (char *) cast to every valid
(foo *).  [ each one *must* yield a distinct (char *)]. The subset, in
general, may be different for different 'foo's ( int, long, double,
struct etc ).

>  ...One interesting
>thing is, by these rules, the use of malloc(), for anything other
>than char arrays, is non-portable.

Because malloc returns a (char *), and (char *)'s don't convert to,
say, (int *)'s, right? Wrong. Malloc doesn't return *any* old (char *),
it returns a (char *) which is guaranteed to be in the subset described
above, for any 'foo' you care to use. Thus malloc is portable. This
is not to say that you don't need to use the cast.

> >> C has been defined such that all members-of-structures share the
> >> same name-space...
> >
> >Not modern C, which puts each structure's members in a separate name space.
>
>If so, most existing programs which use structures will not compile.

All of mine will.
-- 
----------------------------------------------------------------------
Greg Smith     University of Toronto      UUCP: ..utzoo!utcsri!greg
Have vAX, will hack...