我正在尝试使用来自gtree
的{{1}}。
我在s变量中得到错误的值(总是0),同时迭代它:
glib
我像这样设置树:
gboolean iter_all(gpointer key, gpointer value, gpointer data) {
int *s = (int *)value;
printf("\n%s%d \n", (char *)key, *s);
return FALSE;
}
GTree* t = g_tree_new((GCompareFunc)g_ascii_strcasecmp);
readFilec(t);
g_tree_foreach(t, (GTraverseFunc)iter_all, NULL);
我读过的文件看起来像那样:
void readFilec(GTree *tree)
{
FILE *fp = fopen("cfg/file.csv", "rb" );
char * line = NULL;
size_t len = 0;
ssize_t read;
if (fp == NULL)
exit(EXIT_FAILURE);
char *p1;
int p2;
while ((read = getline(&line, &len, fp)) != -1)
{
printf("%s", line);
p1 = strtok(line, "|");
p2 = (int)atoi(strtok(NULL, "|"));
g_tree_insert(tree,(gpointer ) g_strdup(p1), (gpointer ) &p2);
printf("-%s%d ", p1, p2);
}
if (line)
free(line);
//exit(EXIT_SUCCESS);
}
答案 0 :(得分:1)
评论已经确定了问题(您正在向树中插入指向本地堆栈变量的指针),但仍然存在一些不太严重的问题。将int
存储在GTree
中时,最好直接将其用作指针值,例如:
gboolean iter_all(gpointer key, gpointer value, gpointer data) {
int s = (int) value;
printf("\n%s%d \n", (char *)key, s);
return FALSE;
}
...
g_tree_insert(tree, (gpointer) g_strdup(p1), (gpointer) p2);
为避免内存泄漏,您还需要指定一个destroy函数来释放字符串键:
GTree* t = g_tree_new_full((GCompareFunc) g_ascii_strcasecmp,
NULL, g_free, NULL);