I have a binary search tree for which I'm trying to implement an insert function. However when I test the code, I see that no element is getting added at all even though my logic seems fine to me. I feel like there is some C idiosyncrasy that I'm missing.
struct tree_element {
int data;
struct tree_element* left;
struct tree_element* right;
};
typedef struct tree_element node;
void init(node* root){
root->left = NULL;
root->right = NULL;
root->data = 0;
}
void insert(node* root, int val){
if (root == NULL){
root = (node*)(malloc(sizeof(node)));
init(root);
root->data = val;
printf("added %i\n", val);
return;
}
if (val > root->data){
insert(root->right, val);
}
else {
insert(root->left, val);
}
}
insert.insert(root->right, ...you are passing a copy of the right pointer - the value that you (might) assign ininsertnever makes it back out.