【发布时间】:2020-08-25 05:32:51
【问题描述】:
在我学习 C++ 之后,我开始学习一点点 C,所以我使用的是 bintree 实现。
代码:
struct Node {
int value = -1;
struct Node* left = NULL;
struct Node* right = NULL;
};
void insert_tree(int value, Node* root) {
if (root == NULL) {
root = (struct Node*) malloc(sizeof(Node));
root->value = value;
printf("%d\n", root->value);
root->left = NULL;
root->right = NULL;
}
else {
if (root->value >= value) {
insert_tree(value, root->left);
}
else {
insert_tree(value, root->right);
}
}
}
void printTree(Node* root) {
if (root != NULL) {
printf("%i\n", root->value);
printTree(root->left);
printTree(root->right);
}
}
int main() {
Node* root = NULL;
insert_tree(30, root);
printTree(root);
}
在这里我可以看到 insert_tree 如何执行 malloc 并正确分配内存,因此它在 insert_tree 内输出 30,但是当我调用 printTree() 时,树中没有节点。我不知道为什么,因为我传递了节点的左指针,并且它应该不受insert_tree 的上下文的影响。
insert_tree() 这里有什么问题?
【问题讨论】:
标签: c pointers struct binary-search-tree pass-by-reference