假设这个程序:
#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**) (或者只是禁用兼容性检查)?因为我非常想保留有关间接级别的兼容性警告...
最佳答案
为什么不更改方法签名,使其返回新指针而不是通过指针传递它?事实上,就像常规的 malloc
一样:
static void * ring_pool_alloc(size_t n) {
static unsigned char pool[256], i = 0;
void *p = &pool[i];
i += n;
return p;
}
int main(void) {
char *str = ring_pool_alloc(7);
strcpy(str, "foobar");
printf("%s\n", str);
return 0;
}
关于c - 处理双重间接时避免不兼容的指针警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2943983/