5

我有一个k类型的变量const char *,以及一个带有原型的 glib 函数

void g_hash_table_replace(GHashTable *hash_table,
                          gpointer key,
                          gpointer value);

gpointer被简单地定义为

typedef void* gpointer;

我知道在这种情况下,实际上可以k作为 key in传入g_hash_table_replace,但是 gcc 给了我错误

service.c:49:3: warning: passing argument 2 of ‘g_hash_table_replace’ discards ‘const’ qualifier from pointer target type [enabled by default]
/usr/include/glib-2.0/glib/ghash.h:70:13: note: expected ‘gpointer’ but argument is of type ‘const char *’

这是 gcc 4.6.0。在 4.5.0 及更早版本中,对 (char *) 的简单强制转换就足以消除此警告,但 gcc 似乎变得“更聪明”了。我试过(char *)(void *)k了,但它仍然知道该变量最初是const. strdup(3)在不调用的情况下消除此警告的最佳方法是什么k

4

1 回答 1

2

我刚刚用 gcc 4.6.1 试过这个。

#include <glib/ghash.h>
#include <stdio.h>
#include <unistd.h>

const char *k="Testing";

int main(int argc, char **argv)
{

    int val = 1024;

    GHashTable *hash_table=NULL;
    g_hash_table_replace(hash_table,(gpointer) (intptr_t)k, &val);

    return 0;
}

没有演员表,错误就像你上面描述的那样。但是,如果我如上所示将const char*to first 转换为,则警告将被抑制。intptr_t您能否确认您仍然遇到我的代码示例的错误?

于 2011-07-20T15:01:02.453 回答