c - 指向 void 指针的指针需要显式转换

标签 c pointers void-pointers

<分区>

我有以下函数签名

int foo(void **)

并试图给它一个指向 char 指针的指针,即 char **。我的编译器提示以下警告

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

这是可以预料的吗?我知道将 char * 传递给需要 void * 的函数不需要显式强制转换,但对于指向指针的指针是否如此?

注意:这显然是一个 C 问题。如果不同的 C 版本对此有不同的处理方式,我会很感兴趣。

最佳答案

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".

因此,只有 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.

关于c - 指向 void 指针的指针需要显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25161649/

相关文章:

c - 在 C 中将 int 转换为 char 的问题

c++ - 在 C MexFunction 中使用 Besselk 函数

C++ 指向结构的指针失去值(value)

C 编程。仅使用数组和指针生成随机字母字符串的函数

c - void*,字符串和字符的指针

c - C语言中声明void**是什么意思?

c - C中动态确定函数参数的类型?

c++ - 从 32 位和 64 位二进制文​​件读取

c - 为什么这个声明的解引用类型双关指针警告是编译器特定的?

复制指针字符未按预期工作