C语言 双指针转换,使用“const void **ptr”参数传递到函数中



GCC给了我以下警告:

note: expected 'const void **' but argument is of type 'const struct auth **

有没有可能导致问题的情况?

更大的代码段是

struct auth *current;
gl_list_iterator_next(&it, &current, NULL);

函数只是存储在current一些void *指针中。

错误消息非常清楚:您正在传递接受void **struct auth **。这些类型之间没有隐式转换,因为void*可能与其他指针类型具有相同的大小和对齐方式。

解决方案是使用中间void*

void *current_void;
struct auth *current;
gl_list_iterator_next(&it, &current_void, NULL);
current = current_void;

编辑:为了解决下面的评论,这里有一个为什么这是必要的示例。假设你在一个平台上,sizeof(struct auth*) == sizeof(short) == 2 ,而sizeof(void*) == sizeof(long) == 4 ;这是 C 标准允许的,并且实际上存在具有不同指针大小的平台。那么OP的代码将类似于执行

short current;
long *p = (long *)(&current);  // cast added, similar to casting to void**
// now call a function that does writes to *p, as in
*p = 0xDEADBEEF;               // undefined behavior!

然而,这个程序也可以通过引入一个中间long来工作(尽管只有当long的值足够小以存储在short中时,结果才有意义)。

嗯...我认为像const void *这样的结构没有多大意义。

因为如果用户想访问void *下的数据,他需要从 void 进行强制转换,并且此操作绕过编译器类型检查,从而绕过常量。

请考虑以下示例:

#include <stdio.h>
#include <stdlib.h>
int main () {
  int i = 6;
  int * pi = &i;
  const void * pcv = pi;
  const int  * pci = pi;
  // casting avoids type checker, so constantness is irrelevant here
  *(int *)pcv = 7;
  // here we don't need casting, and thus compiler is able to guard read-only data
  *pci = 7;
  return 0;
}

所以结论是我们需要 void 指针 Or 来确保数据的恒定性,但不能两者兼而有之。

最新更新