【发布时间】:2015-02-23 18:14:00
【问题描述】:
我现在正在实施 Barnes-Hut Algorithms 来模拟 N 体问题。我只想问一下 building-tree 部分。
我做了两个函数来为它构建树。
我递归地构建树,并在构建时打印每个节点的数据,一切似乎都是正确的,但是当程序返回主函数时,只有树的根和根的子节点存储值。其他节点的值没有被存储,这很奇怪,因为我在递归期间打印了它们,它们应该已经被存储了。
这里有部分代码经过修改,我认为问题可能出在哪里:
#include<...>
typedef struct node{
int data;
struct node *child1,*child2;
}Node;
Node root; // a global variable
int main(){
.
set_root_and_build(); // is called not only once cuz it's actually in a loop
traverse(&root);
.
}
这里是函数 set_root_and_build():
我已将子指针设置为 NULL,但一开始没有显示。
void set_root_and_build(){
root.data = ...;
..// set child1 and child2 =NULL;
build(&root,...); // ... part are values of data for it's child
}
然后构建:
void build(Node *n,...){
Node *new1, *new2 ;
new1 = (Node*)malloc(sizeof(Node));
new2 = (Node*)malloc(sizeof(Node));
... // (set data of new1 and new2 **,also their children are set NULL**)
if(some condition holds for child1){ // else no link, so n->child1 should be NULL
build(new1,...);
n->child1 = new1;
//for debugging, print data of n->child1 & and->child2
}
if(some condition holds for child2){ // else no link, so n->child2 should be NULL
build(new2,...);
n->child1 = new2;
//for debugging, print data of n->child1 & and->child2
}
}
树中的节点可能有1~2个孩子,这里不是所有的都有2个孩子。
程序在build()函数递归时打印出正确的数据,但是当它返回主函数并调用traverse()时,由于分段错误而失败。
我尝试打印 traverse() 中的所有内容,发现只有 root 和 root.child1、root.child2 存储了我提到的值。
由于我必须多次调用build(),即使是并行调用,new1 和new2 也不能定义为全局变量。 (但我认为它们不会导致这里出现问题)。
有谁知道哪里出错了?
带有调试信息的遍历部分:
void traverse(Node n){
...//print out data of n
if(n.child1!=NULL)
traverse(*(n.child1))
...//same for child2
}
【问题讨论】:
-
这应该标记为 C,而不是 C++
-
是的
malloc()是 C 而不是 C++ -
谢谢大家,我会换标签的。但是我的代码是.cpp文件,这样用malloc还可以吗?
-
能否把traverse()代码贴出来
-
在 cpp 中使用
malloc()是一种不好的做法。你可以改用new1=new Node;
标签: c pointers recursion tree structure