I am trying to make a binary search tree, but when I try to insert any value, or more precisely when a NULL pointer gets passed to the function, it just freezes for a little while and then it crashes. Here's the code:
void create(int co, struct node **leaf){
if(*leaf==0){
(*leaf)=malloc(sizeof(**leaf));
(*leaf)->val=co;
(*leaf)->left=0;
(*leaf)->right=0;
}
else if(co<(*leaf)->val){
create(co, &(*leaf)->left);
}
else if(co>=(*leaf)->val){
create(co, &(*leaf)->right);
}
}
I can't figure out why it does that. Can you explain?
EDIT: The first call of the function looks like this:
struct node *root;
root=0;
for(i=0;i<c;i++){
create(f[i], &root);
}
Where c is the number of elements in the array. And this is the definition of the struct:
struct node{
int val;
struct node *left;
struct node *right;
};
So the problem is not in the code I posted here, the entire code can be found here If I should just rewrite the whole question and just post the whole code here please saz so in the commnets, will try to rectify ASAP.
FOUND MY ANSWER
After I got it to actually get past create
safely, I was able to find the last one mistake that screwed up my program. It was *i++;
. Apparently ++ doesn't work well with values being pointed to. After I rewrote it to *i=*i+1;
it finally works, so I' like to thank all the people who helped me and ask one final question: What is the difference between *i++;
and *i=i+1;
?