我想把一个GSList放在一个GHashTable里面,下面是我如何处理这一切的:

#include <glib.h>
#include <glib/gprintf.h>

typedef struct Foo_ {
  GHashTable * bar;
} Foo;

Foo * create() {
  Foo * foo = g_malloc(sizeof(Foo));
  foo->bar = g_hash_table_new(NULL, NULL);
  return foo;
}

void add_element(Foo * foo, gchar * key, gpointer data) {
  GSList * list = g_hash_table_lookup(foo->bar, key);

  if(list == NULL) {
    // init empty list
    list = g_malloc(sizeof(GSList));
    list->data = NULL;
    list->next = NULL;
  }

  list = g_slist_append(list, data);
  g_hash_table_insert(foo->bar, key, list);
}


void output_content(Foo * foo, gchar * key) {
  GSList * list = g_hash_table_lookup(foo->bar, key);
  guint length = g_slist_length(list); //
  int idx;

  for(idx = 0; idx < length; idx++) {
    int * data = g_slist_nth_data(list, idx);
    g_printf("%d\n", *data); // segfault happens here, cause data == NULL
  }
}

int main() {
  Foo * foo = create();
  int data0 = 0;
  int data1 = 1;
  int data1bis = 11;
  int data1ter = 111;
  int data2 = 2;

  add_element(foo, "data0", &data0);
  add_element(foo, "data1", &data1);
  add_element(foo, "data1", &data1bis);
  add_element(foo, "data1", &data1ter);
  add_element(foo, "data2", &data2);

  output_content(foo, "data1");

  return 0;
}

用编译程序
gcc  -g -Wall -L  -I -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include  -lglib-2.0 -o main main.c

所以这个程序生成一个segfault,我不知道这是怎么发生的,因为我正确地将所有数据添加到列表中,并将列表添加到哈希表中,有什么想法可以解决这个问题吗?

最佳答案

代码的下一部分是错误的,只需删除它

  if(list == NULL) {
    // init empty list
    list = g_malloc(sizeof(GSList));
    list->data = NULL;
    list->next = NULL;
  }`

使用此添加功能:
void add_element(Foo * foo, gchar * key, gpointer data) {
  GSList * list = g_hash_table_lookup(foo->bar, key);

  list = g_slist_append(list, data);
  g_hash_table_insert(foo->bar, key, list);
}

关于c - 如何将GSList放入GHashTable中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3642594/

10-11 20:55