I'm trying to create a method for inserting nodes into a BST with the following structs:
// node structure
struct Node {
int val;
struct Node* left;
struct Node* right;
};
// binary tree structure
struct BinaryTree {
struct Node* root;
};
Originally I created this method for adding nodes to the tree:
// add value to binary tree
void _AddNode(struct Node* node, int val) {
if (node == NULL)
*(&node) = CreateNode(val);
else if (val <= node->val)
_AddNode(node->left, val);
else
_AddNode(node->right, val);
}
void AddNode(struct BinaryTree* tree, int val) {
_AddNode(tree->root, val);
}
Using this function to construct the tree, I get a Segmentation fault: 11 error when I try to traverse, print, access data from the tree.
However, when I modified the function to pass in a double pointer and effectively do the same thing it worked:
// add value to binary tree
void _AddNode(struct Node** node, int val) {
if (*node == NULL)
*node = CreateNode(val);
else if (val <= (*node)->val)
_AddNode(&(*node)->left, val);
else
_AddNode(&(*node)->right, val);
}
void AddNode(struct BinaryTree* tree, int val) {
_AddNode(&tree->root, val);
}
Why does the latter work, but the former doesn't.
*(&node)isn't right.node(as a parameter) is declared local to the function and is equivalent to simplynode._AddNode) are reserved. See e.g. this reserved identifier reference for details.