-
why need to cast void* ?
Currently studying through how pointers work.
I understand void pointer is pointer with no associated data type, which allows it to hold address of any type and can be typecasted to any type.
In example code below, I see &ptrVar being casted to void*.
QUESTION: Why is the (void*) cast necessary? I removed the void* cast and seems like the program still outputs the same result.
Code:
#include <stdio.h>
int main()
{
int intVar = 10;
int *ptrVar = &intVar;
printf("ptrVar address: %p\n", (void*)&ptrVar); // Output the address
printf("value pointed to: %d\n", *ptrVar); // Value at the address pointed
return 0;
}
-
printf(3): formatted output conversion - Linux man page
Because printf expects %p arguments to be explicitly void*
Also, recall that printf is prototyped like so.
int printf(const char *format, ...);
Any parameters which match the ... position are not automatically cast to the correct type (like they would be with an actual prototype declaration), but are instead just promoted using the default promotion rules.
Which means you need to be a little more specific.
> QUESTION: Why is the (void*) cast necessary? I removed the void* cast and seems like the program still outputs the same result.
It probably will, on most machines.
Because most machines have the same pointer representation for all pointer types.
But not all of them -> Question 5.17