You wrote, "this is simple to understand". Clearly it is not. Firstly, you are not casting the data, nothing is happening to the data. Secondly, what you pass to the function with a
vs &a
is totally different. A void pointer is simply a reference to some data. The underlying data type is unknown (to the compiler). Due to this fact, you cannot perform pointer arithmetic for example.
Let's say you malloc() a chunk of memory to store some data and the pointer returned is the value 0x2020 and is assigned to x. Now let's say x is on a region of the stack at memory location 0x1000. This means x is 0x2020. *x is the data you put inside that malloc'd region. Now the important part.. &x is 0x1000 which is the memory address of x and in our hypothetical case, this is on the stack. The following example demonstrates a bit of void *
and void **
. It is just a quick sample and not the correct way to do anything except demonstrate the concept.
#include <stdio.h>
struct t1 { int a; };
struct t2 { int b; };
int testvppa(void **pp){
void *p = *pp;
struct t1 * pt = (struct t1 *)p; // need to cast in order to de-reference
return pt->a;
}
int testvppb(void **pp){
void *p = *pp;
struct t2 * pt = (struct t2 *)p; // need to cast in order to de-reference
return pt->b;
}
int testvp(void *p, int which){
if (which == 1)
{
return testvppa(&p);
}
else{
return testvppb(&p);
}
}
int main(){
struct t1 stuffa = { 123 };
struct t2 stuffb = { 456 };
void * vp;
printf("stuffa: {%d} @ %p\n", stuffa.a, &stuffa);
printf("stuffb: {%d} @ %p\n", stuffb.b, &stuffb);
vp = &stuffa;
printf("vp: %p test: %d\n", vp, testvp(vp,1));
vp = &stuffb;
printf("vp: %p test: %d\n", vp, testvp(vp,2));
return 0;
}
Running on my machine has the following results: (Note the address of the pointers will change but values 123, and 456 will be the same.)
stuffa: {123} @ 0x7fff28116db0
stuffb: {456} @ 0x7fff28116dc0
vp: 0x7fff28116db0 test: 123
vp: 0x7fff28116dc0 test: 456
There's a good chance my answer will be more confusing than enlightening. This is why the actual correct answer to your question is exactly what Oli Charlesworth said in his comment: "I suggest first learning C, and then posting questions"