The following is my code for BST insert function.Could someone explain why this gives a segmentation fault?
#include <stdio.h>
#include <stdlib.h>
struct node{
int value;
struct node* right;
struct node* left;
};
struct node* insert(struct node* n,int age){
if (n==NULL){
n = malloc(sizeof(struct node));
n->value = age;
n->left = n->right = NULL;
}
else if(age < n->value){
n->left = insert(n->left, age);
}
else {
n->right = insert(n->right, age);
}
return n;
}
void main(){
int age;
struct node* n=NULL;
scanf("%d",&age);
while (age!=-1){
n=insert(n,age);
scanf("%d",&age);
}
}
I referred to this and it suggests the use of ** (reference to pointer).
f( &px );
//...
void f( int **px )
{
*px = malloc( sizeof( int ) );
printf( "*px = %p\n", *px );
}
But why can't we avoid the use of ** by changing the return type from void
to node*
?