我正在尝试使用来自glib
的gtree
。
在像这样迭代时,我在 s 变量中得到错误的值(始终为 0):
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);
}
我读到的文件如下所示:
cfg/file.csv
AA1.E|1
AA2.E|2
最佳答案
评论已经指出了问题(您正在将指向本地堆栈变量的指针插入到树中),但仍然存在一些不太严重的问题。当在GTree
中存储int
时,最好直接将其用作指针值,例如:
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);
为了避免内存泄漏,您还需要指定一个销毁函数来释放字符串键:
GTree* t = g_tree_new_full((GCompareFunc) g_ascii_strcasecmp,
NULL, g_free, NULL);
关于c - gtree 中的值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21700853/