Usage of void pointers across different platforms

微笑、不失礼 提交于 2019-11-28 02:47:12

问题


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.



来源:https://stackoverflow.com/questions/26751722/usage-of-void-pointers-across-different-platforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!