Search code examples
cpointersindirection

How to dereference a double void pointer to an int pointer


I have a code that looks somewhat like this:

int num = 5;
int *ptr = #
void **xptr = &ptr;
printf ("values:%d\n",**(int *)xptr); 

Why can't i de-reference a void double pointer,which points to an int pointer ? The below two examples work.

Snippet:1

int *ptr = #
int **xptr = &ptr;
printf ("values:%d\n",**xptr);

Snippet 2:

void *ptr = #
printf ("values:%d\n",*(int *)ptr);

Solution

  • void ** is not a generic pointer unlike void *. Any void ** value you play with must be the address of an actual void * value somewhere. Compiler should raise a warning for void **xptr = &ptr;:

    [Warning] initialization from incompatible pointer type [enabled by default]
    

    You can do it as follows

    int num = 5;
    void *ptr = #
    void **xptr = &ptr;
    printf ("values:%d\n", *((int *)*xptr));  
    

    For more detailed explanation, read comp.lang.c FAQ list · Question 4.9.