gpt4 book ai didi

c - C 中的二叉树 - 问题

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:48 25 4
gpt4 key购买 nike

typedef struct node
{
struct node *leftChild, *rightChild;
int value;
} bst;

void insert(bst* b, int i)
{
b=malloc(sizeof(b));
b->value=i;
b->leftChild = NULL;
b->rightChild = NULL;
printf("[%i]",b->value);
return;
}
main()
{
bst* b;
insert(b,5);
printf("[%i]",b->value);
}

第二个 printf 导致段错误,将其注释掉它工作正常。我在这里做错了什么(忽略函数名称的含义,即插入是 bst 的插入函数)? bst 不应该坚持在插入函数之外进行设置吗?

最佳答案

您需要通过引用传递指针以更改它指向的位置。

// just add this & here in the function definition.
// That's the only change in all your code (for c++)
void insert(bst * &b, int i)

或者在 C 中,一个指针 pointer

void insert(bst ** b, int i)
{
*b=malloc(sizeof(*b));
(*b)->value=i;
(*b)->leftChild = NULL;
(*b)->rightChild = NULL;
printf("[%i]",(*b)->value);
return;
}

注意取消引用指针指针的更改。

当你调用这个函数时,你需要获取你的 bst * 的地址:

insert(&b,5);

关于c - C 中的二叉树 - 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3876162/

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