this is what I read from comp.lang.c, enjoy!
In “Toby Merridan” writes:
>Could some kind soul demonstrate the use of void pointers for me:
>example: void * Pnothing
>When would you youse these?
Seldom, if ever, except as function parameters.
Void pointers have the nice property that they are *automatically*
converted to/from whatever pointer type is required by the context,
so you don’t need to put casts in your code (casts are generally
considered evil in C, especially pointer casts).
Consider malloc(), that returns a void pointer and free(), that takes
a void pointer as argument:
#include
…
int *array = malloc(100 * sizeof(int));
…
free(array);
In the absence of the type void, malloc() would have to return a char
pointer and free() would expect a pointer to char, so the above code
would have to look like this:
int *array = (int *)malloc(100 * sizeof(int));
…
free((char *)array);
Now, imagine that you want to write your own function, that computes
the sum of all the bytes in an object whose address and size are
passed as arguments:
unsigned long bytesum(void *addr, size_t n)
{
unsigned long sum = 0;
unsigned char *p = addr;
for (; n > 0; n–) sum += *p++;
return sum;
}
To get the sum of the bytes of foo, you use bytesum(&foo, sizeof foo),
no matter what is the type of foo.
Note that the addr parameter of the function is pretty useless as such:
it can’t be dereferenced or directly involved in any pointer arithmetic.
This is why the function is using p instead, whose type is adequate for
a byte pointer. If I made the parameter addr of type pointer to unsigned
char, the correct function call would be:
bytesum((unsigned char *)&foo, sizeof foo)
which is clumsier than in my actual implementation.
So, basically void pointers are not adding any new functionality to the
language (anything you can do with a void pointer can also be done with
a pointer to char), but they make your life as a programmer easier, by
removing the need for casts.
Dan
—
Dan Pop
DESY Zeuthen, RZ group
Email: Dan. …@ifh.de