2016-05-23 35 views
0

我在这两种结构:传递一个新节点的指针结构内

typedef struct node { 
    int info; 
    struct node *left, *right; 
}NODE; 

typedef struct bst { 
    NODE *root; 
}BST; 

而这些功能:

NODE *newNode(int info) { 
    NODE *tmp = (NODE *)malloc(sizeof(NODE)); 
    tmp->left = tmp->right = NULL; 
    tmp->info = info; 
    return tmp; 
} 
void addTree(BST **bst, int info) { 
    if (*bst == NULL) { 
     (*bst)->root = newNode(info); // <- Breaks the program 
     return; 
    } 
    else while ((*bst)->root != NULL) { 
     if (info < (*bst)->root->info) 
      (*bst)->root = (*bst)->root->left; 
     if (info >(*bst)->root->info) 
      (*bst)->root = (*bst)->root->right; 
    } 
    (*bst)->root->info = info; // <- Breaks the program 
} 

我想不出有什么我已经做错了。 我打电话这样的功能的主要功能:

addTree(&binST, tmp); 

我用调试器,它给了我不是一个单一的错误或警告。 任何帮助,将不胜感激。

+0

' - >'也是一个解引用运算符,并且不能解引用NULL。 – jxh

回答

1
if (*bst == NULL) { 
    (*bst)->root = newNode(info); // <- Breaks the program 

Excatly问题就出在这里,因为*bstNULL然后在下一行你取消对它的引用(当你试图访问结构成员),这将导致未定义行为和崩溃,你的情况。

在访问结构成员之前,您需要分配内存到*bst。这样的 -

if (*bst == NULL) { 
    *bst=malloc(sizeof(BST));  //allocate memory first and then access struct members 
    (*bst)->root = newNode(info); 

注意 - 请记住,free分配的内存。

+0

这是问题..很多谢谢。 P.S.我已经在主函数中分配内存将工作正常吗? –

+0

@DraganZrilić我想这对root很好,但当你使用递归,所以对于其他节点你需要在这个函数中分配内存,否则会出现同样的问题。 – ameyCU