我現在正在執行Barnes-Hut Algorithms來模擬N體問題。 我只想問建築樹部分。C使用結構指針構造樹
我有兩個功能來爲它構建樹。
我遞歸地構建樹,並在構建時打印每個節點的數據,看起來正確。
但是,當程序返回到主函數時,只有樹的根,並且根的孩子存儲值,其他節點的值不會被存儲,這是奇怪的,因爲我在遞歸過程中打印它們並且它們應該已經被存儲。
下面是與修改的代碼,我認爲問題出在哪裏可能在某些部分:
#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()函數遞歸時打印出正確的數據。
但是,當它回到主函數並調用遍歷()時,由於分段錯誤而失敗。
我試圖在遍歷()中打印所有內容,發現只有root和root.child1,root.child2存儲了我剛剛提到的值。
因爲我要叫建立()幾次,甚至在並行,名new1和NEW2不能被定義爲全局變量...(但我不認爲他們會在這裏的問題)
有誰知道它出錯的地方?
=====================
橫向部分與調試信息:
void traverse(Node n){
...//print out data of n
if(n.child1!=NULL)
traverse(*(n.child1))
...//same for child2
}
這應該被標記爲C,而不是C++ – 2015-02-23 18:19:06
是'的malloc()'是C,而不是C++ – Christophe 2015-02-23 18:20:24
感謝你們,我會改變的標記。 但我的代碼是.cpp文件,如果我像這樣使用malloc,它仍然可以嗎? – cshushu 2015-02-23 18:23:09