Pranay Saha
Pranay Saha

Reputation: 298

what this (int**)&p; mean in the statement?

This code is practice code for pointers. But I am not understanding the (int**)&p; means in this code.

void fun(void *p);

int i;

int main()
{
  void *vptr;
  vptr = &i;
  fun(vptr);
  return 0;
}
void fun(void *p)
{
    int **q;
    q = (int**)&p;
    printf("%d\n", **q);
}

Please elaborate how it is evaluated.

Upvotes: 2

Views: 1190

Answers (2)

Am_I_Helpful
Am_I_Helpful

Reputation: 19158

&p being of type void**, is being casted to type of int** which is to be assigned to q.

SIDE-NOTE : "Any pointer can be assigned to a pointer to void. It can then be cast back to its original pointer type. When this happens the value will be equal to the original pointer value."

Be careful when using pointers to void. If you cast an arbitrary pointer to a pointer to void, there is nothing preventing you from casting it to a different pointer type.

Upvotes: 2

unwind
unwind

Reputation: 399813

It's a type cast, that interprets the value of &p, which has type void **, as instead having type int ** which is the type of the variable the value is stored in.

The cast is necessary, since void ** is not the same as void * and does not automatically convert to/from other (data) pointer types. This can be confusing.

Upvotes: 2

Related Questions