Usage of void pointers across different platforms

2020-02-12 02:04发布

问题:

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);

回答1:

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.



回答2:

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*.



回答3:

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.