C字典和JSON是兩種非常常用的數據結構,它們都可以存儲鍵值對,用于在程序中處理和傳輸數據。下面我們來具體了解一下它們的特點和使用。
一、C字典
C字典是一種哈希表結構,使用鍵值對來存儲數據,可以快速地查找和讀取數據。具體使用方法如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define HASH_SIZE 997 typedef struct hash_entry { char *key; char *value; struct hash_entry *next; } hash_entry; typedef struct hash_table { hash_entry **table; } hash_table; hash_table *hash_create() { hash_table *t = (hash_table *)malloc(sizeof(hash_table)); t->table = (hash_entry **)calloc(HASH_SIZE, sizeof(hash_entry *)); return t; } void hash_destroy(hash_table *t) { int i; for (i = 0; i< HASH_SIZE; i++) { hash_entry *e, *prev = NULL; e = t->table[i]; while (e) { prev = e; e = e->next; free(prev->key); free(prev->value); free(prev); } } free(t->table); free(t); } int hash_func(char *key) { int h = 0; while (*key) { h = (h<< 4) + *key++; unsigned int g = h & 0xf0000000; if (g != 0) { h ^= g >>24; h &= ~g; } } return h % HASH_SIZE; } void hash_set(hash_table *t, char *key, char *value) { int h = hash_func(key); hash_entry *e, *next; for (e = t->table[h]; e != NULL; e = next) { next = e->next; if (strcmp(e->key, key) == 0) { free(e->value); e->value = strdup(value); return; } } e = (hash_entry *)malloc(sizeof(hash_entry)); e->key = strdup(key); e->value = strdup(value); e->next = t->table[h]; t->table[h] = e; } char *hash_get(hash_table *t, char *key) { int h = hash_func(key); hash_entry *e; for (e = t->table[h]; e != NULL; e = e->next) { if (strcmp(e->key, key) == 0) { return e->value; } } return NULL; } int main(int argc, char **argv) { hash_table *t = hash_create(); hash_set(t, "key1", "value1"); hash_set(t, "key2", "value2"); hash_set(t, "key3", "value3"); printf("%s\n", hash_get(t, "key1")); printf("%s\n", hash_get(t, "key2")); printf("%s\n", hash_get(t, "key3")); hash_destroy(t); return 0; }
二、JSON
JSON是一種輕量級的數據交換格式,具有易讀性和易于解析的特點。JSON可以表示數組、對象、字符串、數字、布爾值和null值。具體使用方法如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <jansson.h> int main(int argc, char **argv) { json_t *json = json_object(); json_object_set_new(json, "key1", json_integer(1)); json_object_set_new(json, "key2", json_real(2.0)); json_object_set_new(json, "key3", json_true()); char *json_str = json_dumps(json, JSON_INDENT(2)); printf("%s\n", json_str); json_decref(json); free(json_str); return 0; }
以上就是C字典和JSON的基本介紹和使用方法,希望對讀者們有所幫助。
上一篇python 類對象創建
下一篇vue else