我正在创建一个变量树,但是看似在insert或print_wevr函数中却出现了一个错误。
运行程序时,出现无限循环。
我该怎么办?
/*5 - VarTrees*/
/*var_trees.c*/
#include <stdio.h>
#include <stdlib.h>
#include "var_trees.h"
/*Defining the struture of variable tree.
* The nodes has tree fields:
info: an generic information
first: the first child-node
next: the next sibling-node
*/
struct var_tree{
void* info;
Var_Tree* first;
Var_Tree* next;
};
/*Create the tree*/
Var_Tree* create(void* info)
{
Var_Tree* t = (Var_Tree*) malloc(sizeof(Var_Tree));
t->info = info;
t->first = NULL;
t->next = NULL;
return t;
}
/*Insert a node*/
void insert(Var_Tree* t,Var_Tree* st)
{
st->next = t->first;
t->first = st;
}
/*go_through the tree*/
void go(Var_Tree* t, void (*cb)(void*))
{
Var_Tree* p;
cb(t->info);
for(p = t->first; p != NULL; p = p->next)
go(t,cb);
printf(">");
}
/*Remove a node*/
//void remov(Var_Tree* t, void* info);
/*5 - VarTrees*/
/*main.c*/
#include <stdio.h>
#include <stdlib.h>
#include "var_trees.h"
Var_Tree* create_int(int info)
{
return create(&info);
}
void print_int(void* info)
{
int* t = (int*) info;
printf("<%d",*t);
}
int main(void)
{
Var_Tree* a = create_int(4);
Var_Tree* b = create_int(3);
Var_Tree* c = create_int(23);
Var_Tree* d = create_int(1);
Var_Tree* e = create_int(2);
insert(a,b);
go(a,print_tree);
}
函数create_int
是用于创建字段信息为int的节点的函数。
print_int
是一个回调函数,可打印整数(“ <”为树创建一种文本符号)。
答案 0 :(得分:0)
在go
函数中,您正在进行递归调用,而无需更改最终导致无限递归的参数。
void go(Var_Tree* t, void (*cb)(void*))
{
Var_Tree* p;
cb(t->info);
for(p = t->first; p != NULL; p = p->next)
go(t,cb); //<-----here you are calling the same
function with the same parameter that leads to an infinite loop
printf(">");
}
您应该传递p
的值代替t
。
void go(Var_Tree* t, void (*cb)(void*))
{
Var_Tree* p;
cb(t->info);
for(p = t->first; p != NULL; p = p->next)
go(p,cb); //<----change t to p
printf(">");
}