指针必须显式强制转换为void指针 [英] Explicit cast required to pointer to void pointer
问题描述
我具有以下功能签名
int foo(void **)
,并尝试为其提供指向char
指针的指针,即char **
.我的编译器抱怨以下警告
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 **"
这是可以预期的吗?我知道将char *
传递给期望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?
注意:这显然是一个C
问题.如果不同的C
版本对此处理方式有所不同,我将很感兴趣.
Note : this is explicitly a C
question. I would be interested if different C
versions treat this differently.
推荐答案
第章22:指向指针的指针:
关于指针和内存分配的指针的一个侧面:尽管由
malloc
返回的void *
类型是通用指针",适合于分配给任何类型的指针或从任何类型的指针进行分配,假设类型void **
不是通用指针" .
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".
因此,只有void *
是通用指针. void **
不是通用指针.因此,传递给您的函数的参数必须为void **
类型.
So, only void *
is a generic pointer. void **
is not generic pointer. Therefore the argument passed to your function must be of type void **
.
另请参见 C-FAQ :
C中没有通用的指针对指针类型.
void *
仅作为通用指针,因为当其他指针类型分配给void *
或从void *
分配时,会自动应用转换(如果需要).如果试图间接指向void *
以外的指针类型的void **
值,则无法执行这些转换.当您使用void **
指针值时(例如,当您使用*
运算符访问void **
所指向的void *
值时),编译器无法知道value曾经从其他某种指针类型转换而来.它必须假设它不过是 void *
;它只不过是void *
.它无法执行任何隐式转换.
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.
换句话说,您使用的任何void **
值必须是某个地方实际void *
值的地址;像(void **)&dp
这样的强制类型转换虽然可能会关闭编译器,但它们是不可移植的(甚至可能无法执行您想要的操作;另请参阅问题13.9).如果void **
指向的指针不是void *
,并且其大小或表示形式与void *
不同,则编译器将无法正确访问它.
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.
这篇关于指针必须显式强制转换为void指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!