Reputation: 93
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.
Upvotes: 0
Views: 69
Reputation: 1091
Looks like you're still learning pointers? If so, consider code like this:
int a = 10;
int *b = &a;
int **c = &b;
You get:
c -> b -> a=10
If you pass a to a function and change it, just the value is passed and the original is unchanged:
void fa(int a) { a = 11; }
...
fa(a);
printf("%d\n", a); // -> 10
If you pass b to a function, you can change a, but not b:
void fb(int *b) { *b = 11; b = NULL; }
...
fb(b); // Also works with fb(&a)
printf("%d\n", a); // -> 11
printf("%d\n", *b); // -> 11
If you pass c, you can change a and b:
void fc(int **c) { **c = 11; *c = NULL; }
...
fc(c); // Also works with fb(&b)
printf("%d\n", a); // -> 11
printf("%d\n", *b); // Segmentation fault dereferencing NULL
If you want a function to update a variable, in C++ better to declare it as a reference:
void fa(int& a) { a = 11; }
...
fa(a);
printf("%d\n", a); // -> 11
Upvotes: 1