如何正确寻址-Wcast-qual

发布于 2024-11-19 13:01:18 字数 920 浏览 8 评论 0原文

我有一个 const char * 类型的变量 k,并且在 glib 中

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

定义了一个带有原型 gpointer 的函数,正如

typedef void* gpointer;

我所知道的那样事实上,在这种情况下,可以将 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 *’

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

I have a variable k of type const char *, and a function in glib with the prototype

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

gpointer is defined simply as

typedef void* gpointer;

I know that in this case it is, in fact, okay to pass in k as the key in g_hash_table_replace, however gcc gives me the error

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 *’

this is with gcc 4.6.0. With 4.5.0 and earlier, a simple cast to (char *) sufficed to supress this warning, but gcc seems to have gotten 'smarter'. I've tried (char *)(void *)k, but it still knows that the variable was originally const. What is the best way to silence this warning without calling strdup(3) on k?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹过旳痕迹 2024-11-26 13:01:18

我刚刚用 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* 转换为 intptr_t (如上所示),则警告将被抑制。您能否确认我的代码示例仍然遇到该错误?

I just tried this with 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;
}

Without casts, the error is as you describe above. But if I cast the const char* to intptr_t first as shown above, the warning is suppressed. Can you confirm that you still experience the error with my code sample?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文