处理双重间接时避免不兼容的指针警告
假设这个程序:
#include <stdio.h>
#include <string.h>
static void ring_pool_alloc(void **p, size_t n) {
static unsigned char pool[256], i = 0;
*p = &pool[i];
i += n;
}
int main(void) {
char *str;
ring_pool_alloc(&str, 7);
strcpy(str, "foobar");
printf("%s\n", str);
return 0;
}
...是否可以以某种方式避免 GCC 警告
test.c:12: warning: passing argument 1 of ‘ring_pool_alloc’ from incompatible pointer type
test.c:4: note: expected ‘void **’ but argument is of type ‘char **’
...而不强制转换为 (void**) (或简单地禁用兼容性检查)?因为我非常想保留有关间接级别的兼容性警告......
Assuming this program:
#include <stdio.h>
#include <string.h>
static void ring_pool_alloc(void **p, size_t n) {
static unsigned char pool[256], i = 0;
*p = &pool[i];
i += n;
}
int main(void) {
char *str;
ring_pool_alloc(&str, 7);
strcpy(str, "foobar");
printf("%s\n", str);
return 0;
}
... is it possible to somehow avoid the GCC warning
test.c:12: warning: passing argument 1 of ‘ring_pool_alloc’ from incompatible pointer type
test.c:4: note: expected ‘void **’ but argument is of type ‘char **’
... without casting to (void**) (or simply disabling the compatibility checks)? Because I would very much like to keep compatibility warnings regarding indirection-level...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不更改方法签名,使其返回新指针,而不是通过指针传递它?事实上,就像常规的
malloc
一样:Why don’t you change the method signature such that it returns the new pointer instead of passing it by pointer? In fact, just like regular
malloc
does:更改
ring_pool_alloc
以接收void *
。如果您愿意,您可以在函数中重新转换为void **
。或者在您的具体情况下:
请注意
void **
不能充当通用指针到指针类型。另一方面,与其他指针类型的void *
之间的转换会自动应用。Change
ring_pool_alloc
to receive avoid *
. You can then recast tovoid **
in the function, if you wish.Or in your specific case:
Note that
void **
cannot act as a generic pointer-to-pointer type. On the other hand, convertions from and tovoid *
with other pointer types are applied automatically.只需将:更改
为:
Simply change:
to: