Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of void pointers across different platforms

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);
like image 539
Naseer Avatar asked Nov 05 '14 07:11

Naseer


People also ask

What are the uses of void pointer?

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.

What is void pointer how it can be used explain with an example?

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'

Can we assign a void pointer to an entire pointer?

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.


1 Answers

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.

like image 130
Mohit Jain Avatar answered Nov 01 '22 20:11

Mohit Jain