gpt4 book ai didi

c - 将新节点传递给结构内的指针

转载 作者:行者123 更新时间:2023-11-30 15:08:20 25 4
gpt4 key购买 nike

我有这两个结构:

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

注意 - 请记住释放分配的内存。

关于c - 将新节点传递给结构内的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37398965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com