双指针的转换,突入功能与`常量无效** ptr`参数 [英] Double pointer conversions, passing into function with `const void **ptr` parameter

查看:202
本文介绍了双指针的转换,突入功能与`常量无效** ptr`参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

海湾合作委员会给了我如下因素警告:

GCC gives me folowing warning:

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

是否有任何情况下,它可能会导致问题?

Is there any case, where it could cause problems?

更大的片段是

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

功能刚刚在商店电流一些无效* 指针。

推荐答案

该错误信息是非常明显的:你是通过一个结构AUTH ** 其中一个无效** 被接受。有一个无效*这些类型之间的隐式转换可能不具有相同的尺寸和对齐其他指针类型。

The error message is clear enough: you are passing a struct auth ** where a void ** was accepted. There is no implicit conversion between these types as a void* may not have the same size and alignment as other pointer types.

解决方案是使用一个中间无效*

The solution is to use an intermediate void*:

void *current_void;
struct auth *current;

gl_list_iterator_next(&it, &current_void, NULL);
current = current_void;

修改:为解决下面的评论,这里就是为什么这是必要的一个例子。假设你是在一个平台上,其中的sizeof(结构AUTH *)==的sizeof(短)== 2 ,而的sizeof(无效*)= = sizeof的(长)== 4 ;这是由C标准和平台有不同大小的指针允许实际存在。然后,OP的code将类似于这样

EDIT: to address the comments below, here's an example of why this is necessary. Suppose you're on a platform where sizeof(struct auth*) == sizeof(short) == 2, while sizeof(void*) == sizeof(long) == 4; that's allowed by the C standard and platforms with varying pointer sizes actually exist. Then the OP's code would be similar to doing

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!

不过,这一方案也可制成通过引入一个中间(虽然结果可能才有意义,当的价值足够小到存储)。

However, this program too can be made to work by introducing an intermediate long (although the result may only be meaningful when the long's value is small enough to store in a short).

这篇关于双指针的转换,突入功能与`常量无效** ptr`参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆