I have a structure node
which has 2 pointers small
and large
and an int val
. I intend to make a binary tree out of it later, but before that I just tried to insert only one element in three different ways and then print it.
The 1st way works fine when I use a double ptr during insertion-
struct node
{
struct node *small;
struct node *large;
int val;
};
void insert(node **root, int data)
{
node *ptr=(node*)malloc(sizeof(node));
ptr->val=data;
ptr->large=NULL;
ptr->small=NULL;
if(*root==NULL)
{
*root=ptr;
return;
}
}
void print(node *ptr)
{
cout<<ptr->val;
}
int main()
{
int a[]{5};
node *root=NULL;
insert(&root,a[0]);
print(root);
return 0;
}
In 2nd way the root node is global and single ptr is used during insertion, it also works just fine-
struct node
{
struct node *small;
struct node *large;
int val;
};
node *root=NULL; //root node is global here
void insert(int data)
{
node *ptr=(node*)malloc(sizeof(node));
ptr->val=data;
ptr->large=NULL;
ptr->small=NULL;
if(root==NULL)
{
root=ptr;
return;
}
}
void print()
{
cout<<root->val;
}
int main()
{
int a[]{5};
node *root=NULL;
insert(a[0]);
print();
return 0;
}
In the 3rd way root node is not global and a single ptr is used during insertion. But this time it gives some runtime error-
struct node
{
struct node *small;
struct node *large;
int val;
};
void insert(node *root, int data)
{
node *ptr=(node*)malloc(sizeof(node));
ptr->val=data;
ptr->large=NULL;
ptr->small=NULL;
if(root==NULL)
{
root=ptr;
return;
}
}
void print(node *root)
{
cout<<root->val;
}
int main()
{
int a[]{5};
node *root=NULL;
insert(root,a[0]);
print(root);
return 0;
}
I don't understand what the issue is with the 3rd approach and how is it different from the other two? I'm using the DevC++ compiler.