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

Passing a new node to a pointer within a structure

我有这两个结构:

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);

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

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

问题出在这里,因为 *bstNULL 然后在下一行你 取消引用它(当你尝试访问结构成员时)导致 未定义的行为 并在您的案例中崩溃。

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

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

注意 - 记得free分配内存。