glib 哈希调用
glib: linux 编译调用
gcc main.c `pkg-config --libs --cflags glib-2.0` -o main
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | #include <stdio.h> #include <glib.h> #include <stdlib.h> #include <string.h> typedef struct _Node { char key[32]; char value[32]; }Node; static void displayhash(gpointer key, gpointer value, gpointer user_data) { printf ( "user_data:%s\n" ,user_data); printf ( "key:%s value:%s\n" ,key,value); } static void destroy_key(gpointer hash_data) { printf ( "destroy key:%s\n" ,hash_data); //因为我这里的键是数组形式不是指针所以不用释放内存。我就直接清空吧 /* free(hash_data); hash_data = NULL;*/ memset (hash_data,0, sizeof (hash_data)); } static void destroy_value(gpointer hash_data) { printf ( "destroy value:%s\n" ,hash_data); //因为我这里的值是数组形式不是指针所以不用释放内存。我就直接清空吧 /* free(hash_data); hash_data = NULL;*/ memset (hash_data,0, sizeof (hash_data)); } /*用来创建每个节点。每个键值对都需要有自己的内存*/ Node *create_node( char *key, char * value) { Node *node = NULL; node = malloc ( sizeof (Node)); if (node == NULL) { return NULL; } memset (node,0, sizeof (Node)); strcpy (node->key,key); strcpy (node->value,value); return node; } int main() { char buff[32] = {0}; static GHashTable *g_hash = NULL; g_hash = g_hash_table_new_full(g_str_hash, g_int_equal, destroy_key, destroy_value); Node *node = create_node( "name" , "xcy" ); if (node != NULL) g_hash_table_insert(g_hash, &node->key, &node->value); Node *node1 = create_node( "age" , "18" ); if (node1 != NULL) g_hash_table_insert(g_hash, &node1->key, &node1->value); Node *node2 = create_node( "sex" , "man" ); if (node2 != NULL) g_hash_table_insert(g_hash, &node2->key, &node2->value); Node *node3 = create_node( "id" , "00001" ); if (node3 != NULL) g_hash_table_insert(g_hash, &node3->key, &node3->value); memcpy (buff, "this is parm" ,12); if (NULL != g_hash) { g_hash_table_foreach(g_hash, displayhash, buff); } printf ( "------------------free hashtable------------------------\n" ); g_hash_table_destroy(g_hash); } |
分类:
学习中
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2022-04-06 CreateFile INVALID_HANDLE_VALUE
2022-04-06 BYTE miniwindef.h
2022-04-06 写代码与英语
2020-04-06 qt addStretch 伸缩量