In the line "no, no, no", why can not we respect P, since P was assigned the real type of pointer q?
int a =2, *q = a, *r; //line 1 void *p; //line 2 p = q; // line 3 r = p; // line 4
Using line 3 above, you assign the pointer q to p . But it does not change the type of p - it is still a pointer to the void. Therefore, you cannot play it. Therefore, the following is not permissible:
printf("%d\n", *p);
Alternatively, you can:
printf("%d\n", *((int*) p));
The above is true. Because we translate p to int * before dereferencing. Consider an example
void func(void *p) {
You can comment on line1 or line2, but still in func() know if p points to long or int data? This is no different from your case.
But before accessing the data that it points to, conversion from void * to type * (data pointer) is always required. Please note that this cannot be a data pointer. For instance,
int i = 42; float f = 4.0; void *p = &f; printf("%d\n", *((int*))p);
It's illegal. p points to a float * . The dereferencing parsing, as if it were pointing to int data, is incorrect.
In the string "?", Is it legal to point to a pointer to an integer?
printf("%d\n", (int) *p);
Since p is void* , you are not allowed to play in the first place. Casting after dereferencing does not change anything, and dereferencing is illegal.
If you were to point the pointer like:
printf("%d\n", (int)p);
This implementation-defined behavior in C. C also provides intptr_t / uintptr_t for converting integers to pointers.