c语言 - 使用 GLib 的 GArray 存储"结构"并检索数据



我正在尝试使用 GLib 作为编写自己的数据结构的替代方案。我的目标是仅使用 glib 编写基于邻接列表的简单图形数据结构。

现在的代码如下

#include <glib.h>
#include <glib/gprintf.h>
struct graph
{
GArray * nodes;
};
struct node
{
GArray * neighbors;
gint weight;
GString * label;
};
struct neighbor
{
struct node * dst;
gint weight;
};
struct graph * graph_new(void);
void graph_node_add(struct graph * graph, const gchar * label, gint weight);
void graph_edge_add(struct graph * graph, struct node * src, struct node * dst, gint weight);
struct graph * graph_new(void)
{
struct graph * g = g_new(struct graph, 1);
g->nodes = g_array_new (FALSE, FALSE, sizeof (struct node));
return g;
}
void graph_node_add(struct graph * graph, const gchar * label, gint weight)
{
struct node * node = g_new(struct node, 1);
node->neighbors = g_array_new(FALSE, FALSE, sizeof (struct neighbor));
node->label = g_string_new(label);
node->weight = weight;
graph->nodes = g_array_append_val(graph->nodes, node);
}
void graph_edge_add(struct graph *graph, struct node *src, struct node *dst, gint weight)
{
struct neighbor * neighbor = g_new(struct neighbor, 1);
neighbor->dst = dst;
neighbor->weight = weight;
src->neighbors = g_array_append_val(src->neighbors, neighbor);
}

int main(void)
{
struct graph * G = graph_new();
graph_node_add(G, "u", 10);
graph_node_add(G, "v", 20);
graph_node_add(G, "w", 15);
struct node * n = &g_array_index(G->nodes, struct node, 0);
g_printf("segfaulting heren");
char * s = n->label->str;
g_printf("LABEL %sn", s);
return(0);
}

struct node检索GString时出现段错误(第 59 行左右(。

由于我从GLib开始,任何更好的方法来处理我的目标都是受欢迎的。

请注意,我编写了释放内存的函数,这只是为了使这个问题中的源代码更小。

在 Linux 上,代码可以编译为:

gcc `pkg-config --cflags --libs glib-2.0` -o graph graph.c

发生这种情况是因为在 graph_node_add(( 中,您最终会添加一个指向数组的指针,而不是您想要添加的数据。

这样的东西可能会起作用:

struct node node;
node.neighbors = g_array_new(FALSE, FALSE, sizeof (struct neighbor));
node.label = g_string_new(label);
node.weight = weight;
graph->nodes = g_array_append_val(graph->nodes, node);

最新更新