处理双重间接时,避免使用不兼容的指针警告

时间:2010-05-31 13:55:44

标签: 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 **)(或者只是禁用兼容性检查)?因为我非常希望保留关于间接级别的兼容性警告...

3 个答案:

答案 0 :(得分:3)

为什么不更改方法签名,使返回新指针而不是通过指针传递?事实上,就像常规的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;   
}

答案 1 :(得分:2)

更改ring_pool_alloc以获得void *。如果愿意,您可以在函数中重新转换为void **

或者在您的具体案例中:

/* You can pass any pointer as a first parameter */
static void ring_pool_alloc(void *r, size_t n) {
    unsigned char **p = r; /* no cast necessary */
    static unsigned char pool[256], i = 0;
    *p = &pool[i];
    i += n;
}

请注意,void **不能充当通用指针指针类型。另一方面,自动应用与void *和其他指针类型的转换。

答案 2 :(得分:1)

简单地改变:

static void ring_pool_alloc(void **p, size_t n) {

为:

static void ring_pool_alloc(char **p, size_t n) {