c - 处理双重间接时避免不兼容的指针警告

标签 c type-conversion compiler-warnings casting void-pointers

假设这个程序:

#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/

相关文章:

c - 应用程序崩溃,但没有生成核心转储

c - 在数据类型之间切换

c - 当您在 C 中将两种不同的类型相加时会发生什么?

xml - 如何在 Clojure 中将 XML 转换为 edn?

java - TreeMap 通用参数警告

java - 如何在 java 中创建自定义编译器警告?

c - 为什么可变参数宏会给我一个错误?

c++ - gcc 4.7.1 构建以 undefined reference 结束

c - 在 C 中查找 1 到 300 之间的素数

C++:即使使用 "this"关键字,参数声明也会隐藏类成员