I have heard that pointers should first be cast to void to ensure consistency of values across different platforms and should use %p
format specifier. Why is it and what exactly are the problems?
int x=100;
int *pi=&x;
printf("value of pi is: %p",(void*)pi);
printf
is a variadic function and must be passed arguments of the right types. The standard says %p
takes void *
.
Implicit cast doesn't take place for variadic functions.
Quoting from N1570 7.21.6.1 The fprintf function
p : The argument shall be a pointer to void. The value of the pointer is
converted to a sequence of printing characters, in an implementation-defined
manner.
Internal presentation or size of different pointer types is not necessarily same.
For example on one system sizeof(void*)
may be 2, but sizeof(int*)
is 1.
Since printf
is variable argument function, it cannot check the types of incoming parameters. If you passed int*
to it, it would read wrong number of bytes, because it expects void*
.
p
conversion specification in printf
requires an argument of type void *
. C says if you pass an argument of an other type the call invokes undefined behavior.
Besides that, pointer objects of different types are not required to have the same representation: C does not guarantee that sizeof (void *) == sizeof (int *)
for example. C only guarantees that void *
has the same representation as pointers to character types.