05 February 2010

How to use void* in C?

A void pointer can accept (being assigned) any type of pointers without the need of casting:
int x = 2, y = 3, z = 4;
int *p = &x, *q;
void *r = p;
But to assign a void pointer to a typed pointer, you have to explicitly do the casting:
q = (int *) r;
And you cannot dereference a void pointer: '*r' is an compile time error! However,
z = * ((int *) r);
is OK. And z is now equal to 2.

No comments: