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);
We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.
A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type. int a = 10; char b = 'x'; void *p = &a; // void pointer holds address of int 'a' p = &b; // void pointer holds address of char 'b'
In C, we can assign the void pointer to any other pointer type without any typecasting, whereas in C++, we need to typecast when we assign the void pointer type to any other pointer type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With