char* vs void*

Chip Salzenberg chip at tct.uucp
Sat Dec 29 07:34:26 AEST 1990


According to dbrooks at osf.org (David Brooks):
>In article <2778A795.6E71 at tct.uucp> chip at tct.uucp (Chip Salzenberg) writes:
>>The ANSI C standard requires that |char *| and |void *| have identical
>>representations.
>
>I don't understand.  In the case of void*, what is being represented?

The address of an object.  ("Object" explicitly excludes functions.)

>I mean, what semantic commonality is there between the object pointed
>at by a char* and the unobject pointed at by a void* that allows you
>to make this statement?

Pointers of types |char *| and |void *| must both be able to hold the
address of any object.  The reason why this is so differs for the two
types.  For |char *| it's existing practice, and for |void *| it's the
decree of ANSI.

Existing practice for |char *| requires it to be able to hold the
address of any object, since any object type may be allocated with
malloc(), and pre-ANSI malloc() returned a |char *|.  Were ANSI C a
brand new language, |char *| might not have had that property, but
given existing practice, it does.  We can't afford to break all those
dusty decks.

When ANSI invented |void *|, they made it capable of holding any
pointer.  Since |void *| can hold any pointer, and |char *| can hold
any pointer, there would be no point (:-)) in an implementation giving
them different representations.  So ANSI went that final step and
_required_ that their representations be identical.

>Do you mean "can be converted to each other and back without loss of
>information?"

Yes, and that's the important point for this discussion.  A portable
qsort() can cast its |void *| array parameter to |char *| to do
pointer arithmetic, then cast the results of the pointer arithmetic
back to |void *| to generate the comparison function's arguments.
-- 
Chip Salzenberg at Teltronics/TCT     <chip at tct.uucp>, <uunet!pdn!tct!chip>
"Please don't send me any more of yer scandalous email, Mr. Salzenberg..."
		-- Bruce Becker



More information about the Comp.lang.c mailing list