c - 如何将数据从 GHashTable 存储到 C 中的结构

标签 c struct glib

我正在尝试遍历我的哈希表并将键和值存储到一个结构数组中。我不断遇到段错误。我猜是由于基于指针的结构。

当我应该使用指向结构的指针和结构数组时,我仍然感到困惑。

编辑:让它工作。请参阅下面的答案。

最佳答案

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

typedef struct st { 
    char *key;
    char *str;
    int len;
} MyStruct;

int z = 0;
static void hash2struct (gpointer key, gpointer value, gpointer data) {
    MyStruct **s = data; 
    gchar *k = (gchar *) key;
    gchar *h = (gchar *) value;
    s[z]->key = strdup(k);
    s[z]->str =strdup(h);
    z++;
}

int main(int argc, char *argv[]){
    int i;

    GHashTable *hash = g_hash_table_new(g_str_hash, g_str_equal);

    g_hash_table_insert(hash, "Virginia", "Richmond");
    g_hash_table_insert(hash, "Texas", "Austin");
    g_hash_table_insert(hash, "Ohio", "Columbus");

    MyStruct **s = malloc(sizeof(MyStruct) * 3);
    for(i = 0; i < 3; i++) {
        s[i] = malloc(sizeof(MyStruct)); 
    }
    g_hash_table_foreach(hash, hash2struct, s); 

    for(i = 0; i < 3; i++)
        printf("%s %s\n", s[i]->str, s[i]->key);

    for(i = 0; i < 3; i++) {
        free(s[i]->str);
        free(s[i]->key);
        free(s[i]);
    }
    free(s);
    g_hash_table_destroy(hash);
    return 0;
}

关于c - 如何将数据从 GHashTable 存储到 C 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13782997/

相关文章:

linux - 如何找到旧版本 GLIB 的安装位置?

c - 未初始化的数组变量发生了什么?

c++ - FFTW 高级布局——inembed=n 和 inembed=NULL 给出不同的结果?

c - C for循环优化

c - 如何定义不支持输入参数同时支持输入参数的宏函数

c - 使用 readdir_r 读取目录中的文件并使用 qsort 排序

struct - 指向结构 slice 的预期指针

c - 可以运行多个主循环吗?

c - 在C中离开for循环后丢失结构数组中的值

gstreamer - 如何从 gstreamer 中检索错误消息? (C API)