I wonder why is it necessary to cast a void
pointer to an int *
or char *
before printing the contents of the address in memory, even though we tell the printf()
function how to interpret the data in memory?
Let's say that we have the following code:
int main (void)
{
void* c = malloc(4);
printf("%d",*c);
return 0;
}
Why it is not possible to do this?
So to be clear my question is what is the reason for this being not possible?
EDIT: After all the answers and research I am still not convinced exactly where the fatal error in the compilation is. The main reason I am confused is that my compiler (gcc) only gives a WARNING when telling about "dereferencing a void pointer". Is this the actual error? From what I know the program should still compile even with warnings.
EDIT2 I am still confused about the reasons for which we have an ERROR and a WARNING that appear to be completely separate but are generated by the same piece of code:
pointer.c:7:13: warning: dereferencing 'void *' pointer
printf("%d",*p);
^~
pointer.c:7:13: error: invalid use of void expression
printf("%d",*p);
Some users say that the error appears only when we try to use the result of the derefenciation and that the WARNING is when we actually alocate memory for the VOID pointer.
This is clearly NOT the case since if we remove the printf line we do indeed get only a warning but a COMPLETELY UNRELATED ONE.
pointer.c:6:8: warning: unused variable 'p' [-Wunused-variable]
void * p=malloc(4);