我正在尝试使用来自gtree
的glib
。
我在迭代时在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
最佳答案
该注释已经确定了问题(您正在将指向本地堆栈变量的指针插入树中),但是仍然存在一些不太严重的问题。将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);
为避免内存泄漏,还需要指定销毁函数以释放字符串键:
GTree* t = g_tree_new_full((GCompareFunc) g_ascii_strcasecmp,
NULL, g_free, NULL);
关于c - gtree中的值错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21700853/