我有以下函数签名
int foo(void **)
并试图给它一个指向 char
指针的指针,即 char **
。我的编译器提示以下警告
argument of type "char **" is incompatible with parameter of type "void **"
这是可以预料的吗?我知道将 char *
传递给需要 void *
的函数不需要显式强制转换,但对于指向指针的指针是否如此?
注意:这显然是一个 C
问题。如果不同的 C
版本对此有不同的处理方式,我会很感兴趣。
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".
因此,只有 void *
是通用指针。 void **
不是通用指针。因此,传递给函数的参数必须是 void **
类型。
另见 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.