问题
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 bymalloc, is a "generic pointer," suitable for assigning to or from pointers of any type, the hypothetical typevoid **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 fromvoid *'s; these conversions cannot be performed if an attempt is made to indirect upon avoid **value which points at a pointer type other thanvoid *. When you make use of avoid **pointer value (for instance, when you use the*operator to access thevoid *value to which thevoid **points), the compiler has no way of knowing whether thatvoid *value was once converted from some other pointer type. It must assume that it is nothing more than avoid *; it cannot perform any implicit conversions.In other words, any
void **value you play with must be the address of an actualvoid *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 thevoid **points to is not avoid *, and if it has a different size or representation than avoid *, 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