我有一个k类型的变量const char *,以及glib中的原型函数
void g_hash_table_replace(GHashTable *hash_table,
gpointer key,
gpointer value);
Run Code Online (Sandbox Code Playgroud)
gpointer 被简单地定义为
typedef void* gpointer;
Run Code Online (Sandbox Code Playgroud)
我知道在这种情况下,实际上可以k将密钥作为密钥传入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 *’
Run Code Online (Sandbox Code Playgroud)
这是用gcc 4.6.0.对于4.5.0及更早版本,一个简单的转换为(char*)足以抑制此警告,但gcc似乎已经变得"更聪明"了.我试过了(char *)(void *)k,但它仍然知道变量是最初的const.什么是沉默不调用此警告的最佳方式strdup(3)上k?
我刚刚用 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;
}
Run Code Online (Sandbox Code Playgroud)
如果没有强制转换,错误将如您上面所描述的那样。但是,如果我将 转换const char*为intptr_t第一个(如上所示),则警告将被抑制。您能否确认我的代码示例仍然遇到该错误?