我爲我的程序構建了一個二叉搜索樹。這是我的代碼:struct遞歸內存處理問題
struct node {
int steps;
int x;
int y;
struct node *left;
struct node *right;
}*head;
typedef struct node *Node;
Node createStepsBinaryTree(Node head, int newStepsInt, int x, int y){
if (head == NULL) {
head = (Node)malloc(sizeof(Node));
if (head==NULL) {
return NULL;
}else{
head->steps = newStepsInt;
head->x = x;
head->y = y;
head->left = head->right = NULL;
}
}else{
if (head->steps > newStepsInt) {
head->left = createStepsBinaryTree(head->left, newStepsInt, x, y);
}else{
head->right = createStepsBinaryTree(head->right, newStepsInt, x, y);
}
}
return head;
}
這是我從另一個調用遞歸函數此功能:
Coor insertDataToTree(Node stepsTree,Coor root, int x, int y, int map[length][length], int steps){
steps++;
stepsTree = createStepsBinaryTree(stepsTree, steps, x, y);
.
.
.
這是如何我就進入到遞歸函數:
Node stepsTree = NULL;
root = insertDataToTree(stepsTree,root, startPoint.x, startPoint.y, map, startPoint.steps);
現在我遇到的主要問題是: 它運行得非常好,前兩次運行,但第三次運行通過樹中的兩個結構,但它應該在什麼時候運行給自己一個NULL結構它給了一些真正接近NULL的東西。它顯示(節點*)0x000000000000000000001。
有誰知道我該如何阻止這種瘋狂? :)
'head =(Node)malloc(sizeof(Node));'爲指針分配足夠的空間,指向整個結構。 (這個問題可能是由隱藏在typedef後面的指針造成的混淆造成的) – wildplasser
如果你刪除(不必要的)'malloc()'的結果轉換,這是否會給你一個警告呢? – alk
'sizeof(* head)'而不是'sizeof(Node)'可能更適合你。 – WhozCraig