将新节点传递给结构中的指针

时间:2016-05-23 19:24:41

标签: c iteration binary-tree nodes

我有这两种结构:

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
}

我无法弄清楚我做错了什么。 我在main函数中调用了这样的函数:

addTree(&binST, tmp);

我使用过调试器,它没有给我一个错误或警告。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

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

激动人心的问题在于,*bstNULL,然后在下一行中取消引用它(当您尝试访问struct成员时),这会导致未定义的行为 并在你的情况下崩溃。

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

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

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