Explicit cast required to pointer to void pointer [duplicate]

徘徊边缘 提交于 2019-12-19 11:15:32

问题


I have the following function signature

int foo(void **)

and am trying to give it a pointer to a char pointer, i.e. char **. My compiler is complaining with the following warning

argument of type "char **" is incompatible with parameter of type "void **"

Is this to be expected? I know passing a char * to a function expecting a void * requires no explicit cast but is this true for pointers to pointers?

Note : this is explicitly a C question. I would be interested if different C versions treat this differently.


回答1:


Chapter 22: Pointers to Pointers:

One side point about pointers to pointers and memory allocation: although the void * type, as returned by malloc, is a "generic pointer," suitable for assigning to or from pointers of any type, the hypothetical type void ** is not a "generic pointer to pointer".

So, only void * is a generic pointer. void ** is not generic pointer. Therefore the argument passed to your function must be of type void **.

Also see C-FAQ:

There is no generic pointer-to-pointer type in C. void * acts as a generic pointer only because conversions (if necessary) are applied automatically when other pointer types are assigned to and from void *'s; these conversions cannot be performed if an attempt is made to indirect upon a void ** value which points at a pointer type other than void *. When you make use of a void ** pointer value (for instance, when you use the * operator to access the void * value to which the void ** points), the compiler has no way of knowing whether that void * value was once converted from some other pointer type. It must assume that it is nothing more than a void *; it cannot perform any implicit conversions.

In other words, any void ** value you play with must be the address of an actual void * value somewhere; casts like (void **)&dp, though they may shut the compiler up, are nonportable (and may not even do what you want; see also question 13.9). If the pointer that the void ** points to is not a void *, and if it has a different size or representation than a void *, then the compiler isn't going to be able to access it correctly.



来源:https://stackoverflow.com/questions/25161649/explicit-cast-required-to-pointer-to-void-pointer

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