本文介绍了用双间接打交道时避免不兼容的指针警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设此程序:

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

推荐答案

你为什么不改变方法签名,使得它的返回的新指针,而不是通过指针传递呢?事实上,就像普通的的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:

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;
}

这篇关于用双间接打交道时避免不兼容的指针警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 07:51