uses of void

karl at haddock karl at haddock
Sat Aug 16 07:07:00 AEST 1986


sdchem!tps writes:
>sort( (void *)&foo[0], (void *)&foo[20], sizeof(foo), compare_foos );

First, I think you want sizeof(foo_type) or sizeof(foo[0]).

>void *beg, *end;
>int   nelements = (end - beg) / size;

>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 *".

The "abstract units" of sizeof() are "char" by definition.  (Too many users
have been assuming sizeof(char)==1, so it's official in C++ and ANSI C.  I
wish it had been measured in BITS in the first place!)  Since "void *" means
"pointer to object of unknown type", you can't do pointer arithmetic with it.

What you really want is "((char *)end - (char *)beg) / size".  (Don't use int
or long!)

Karl W. Z. Heuer (ihnp4!ima!haddock!karl), The Walking Lint



More information about the Comp.lang.c mailing list