我试图使用递归从文本文件中读取树。我已经调试了函数内部的每个步骤,并且返回了有效的根指针。但是,当我在主函数中将返回节点指针设置为root时,root是空指针。这是为什么?
node *treeRead(FILE *fp) {
char readIn[100];
char questionOnode[40];
char content[100];
char *get = NULL; // the return value for fgets()
node *ptr;
ptr = NULL;
get =fgets(readIn,sizeof(readIn),fp);
if ( get == NULL )
return NULL;
else {
ptr = malloc ( sizeof(node));
sscanf(readIn,"%[^:]:%[^\n]",questionOnode,content);
// if the line started with "question"
if ( !strcmp(questionOnode,"question")){
//fill ptr from the input line read in above
ptr->question = content;
printf("question:%s\n",content);
//read its children
ptr->yes = treeRead(fp);
ptr->no = treeRead(fp);
}
else{//the line started with "object"
ptr->name = content;
printf("object:%s\n",content);
ptr->yes = NULL;
ptr->no = NULL;
}
return ptr;
}
int main()
{
// here omit the open file parts and node structure definition,
// fp is the file pointer to the text file.
node *root = malloc(sizeof(node));
root = treeRead(fp);
}
我怎样才能得到树的根?
最佳答案
程序中没有任何内容调用fopen()
。因此,您的树将是无效的,因为您将永远不会读取任何节点。
(重读-您的程序实际上不会编译。请努力尝试)
关于c - 创建后我怎么还记得树的根,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33903871/