uses of void

guy at sun.UUCP guy at sun.UUCP
Tue Aug 12 04:33:33 AEST 1986


> I want to be able to use "void *" in a generic sorting function and I tried
> something like
> 	.
> 	.
> 	.
> My compiler (4.2BSD running on a Celerity) when into an infinite loop trying
> to parse
> 
> 		(end - beg)

Unfortunately, PCC doesn't really implement "void *".  Other compilers may
not do so either (I don't know if Celerity's compiler is PCC-based or not).
PCC doesn't catch it as illegal, but it doesn't handle it properly either
(the internal coding for the type "void *" is also used as a special
internal indication; since, at the time, the language didn't say "void *"
was OK, *obviously* nobody was going to use it so *obviously* there was no
need to make sure nobody did, right? :-().

> I (naively?) thought that pointer arithmetic would work with "void *", and
> that it would work in the same abstract units as "sizeof()", so that all
> previous generic "char *" kludges could be replaced by "void *".
> 
> What are the (proposed and current) legal operations for "void *" besides
> assignment, casting, and passing as a parameter?

There are no currently legal operations involving "void *" since K&R doesn't
describe "void *" and since PCC, at least, doesn't really implement it.
(It's not impossible to implelement in PCC, but you do have to shuffle the
type coding around to allow another bit for the base type or find some other
value to use for what the encoding of "void *" is used for now.)  The ANSI C
draft of August 11, 1985 doesn't directly say anything about subtracting two
pointers of type "void *".  What it *does* say is

	If two pointers that do not point to members of the same
	array object are subtracted, the behavior is undefined.

and since you can't define an array of "void", no two pointers to "void" can
point to members of the same array object (note: "X points to Y" is
different from "X contains the address of Y", since if X points to Y X must
have the type "pointer to type of Y") so the meaning of the difference
between two pointers to "void" is undefined.

If you use

	int	nelements = ((long)end - (long)beg) / size;

it might work, although it's not guaranteed by the language (things might
get messy if you try raw arithmetic on an implementation where pointers
contain data other than a machine address, like type fields, ring numbers,
etc., etc.).  Note that "qsort" takes a count of elements, rather than a
pointer to the last element; this interface is easier to describe without
stepping outside the bounds of C.
-- 
	Guy Harris
	{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
	guy at sun.com (or guy at sun.arpa)



More information about the Comp.lang.c mailing list