J
James Kuyper
Chad said:[...]
void* can be used as a generic pointer type. What that means is thatAnd if that is correct, should we ever use void ** ?
a value of any pointer type (other than a pointer-to-function type)
can be converted to void* and back again without loss of information.
You might think that void** is therefore a generic pointer-to-pointer
type, but it isn't; in fact, there is no generic pointer-to-pointer
type.
You can convert an int*, or an int**, or an int***, or ... to void*
without loss of information -- except that you lose the type
information, which you have to carefully keep track of yourself.
--
How would you track the type information in this case?
Thats pretty much up to you. There's no way to do it in absolute
generality, but if you have a small list of possibilities that are
relevant to the question, then the following is one example of how to do it:
#include <stdlib.h>
enum typecode { INTP /* many other codes */ };
struct multipointer {
enum typecode pointed_at;
void *pointer;
};
struct multipointer *multipointer_from_intpp(int **ipp)
{
struct multipointer *p = malloc(sizeof *p);
if(p)
{
p->pointed_at = INTP;
p->pointer = ipp;
}
return p;
}
void use_multipointer(struct multipointer *p)
{
if(p==NULL)
return;
switch(p->pointed_at)
{
case INTP:
{
int **ipp = (int **)p->pointer;
// code which works with ipp, such as
if(ipp && ipp[0])
**ipp = 0;
}
break;
// many other cases, including a default:
}
}