gpt4 book ai didi

c - g_hash_table_contains 返回意外值

转载 作者:行者123 更新时间:2023-11-30 17:03:00 25 4
gpt4 key购买 nike

我的这段代码有问题。我无法得到我预期的答案。我搜索过这个,但找不到任何东西。我找不到我的错误..

这是我使用 g_hash_table 的代码

# include <stdio.h>
# include <glib.h>
# include <stdlib.h>

GHashTable *hash = NULL;

int check_sth_blacklist(char *sth)
{
return g_hash_table_contains(hash,sth);
}

main()
{
hash = g_hash_table_new(g_str_hash,g_str_equal);

char *sth = (char*) malloc(32);

scanf("%s",sth);
g_hash_table_add(hash,sth);


scanf("%s",sth);

printf("%d\n",check_sth_blacklist(sth + sizeof(char)*2));


free(sth);
}

在我的输入中我写的是:

cde
abcde

我认为cde字符串将添加到g_hash_table。然后当我在 abcde 中请求字符串 cde 时,它返回 0 值。

最佳答案

我相信,当您将 malloc 的字符串传递到 g_str_hash 下的 GHashTable 时,您会将字符串的控制权移交给哈希表 - 当时间到了,等等。即您不应该再次使用该空间分配!

创建一个新字符串进行比较:

#include <stdio.h>
#include <glib.h>
#include <stdlib.h>
#include <string.h>

GHashTable *hash = NULL;

int check_sth_blacklist(char *sth)
{
return g_hash_table_contains(hash, sth);
}

int main()
{
hash = g_hash_table_new(g_str_hash, g_str_equal);

char *sth = (char*) malloc(32);

scanf("%s", sth);
g_hash_table_add(hash, sth);

char *nth = (char*) malloc(32);
scanf("%s", nth);

printf("%d\n", check_sth_blacklist(nth + 2));

free(nth);

g_hash_table_destroy(hash);

return 0;
}

让哈希管理您放入其中的任何字符串(键或值),当哈希本身被销毁时,所有这些字符串都应该是独立且可释放的。运行时,这给了我:

bash-3.2$ ./a.out
cde
abcde
1
bash-3.2$

关于c - g_hash_table_contains 返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36313337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com