-1

"I was trying to assign NULL to a pointer root in a function. But it doesn't really get assigned by NULL using function. But when I tried to assign root = NULL in main it get assigned. I am not getting why it happens so?

#include<bits/stdc++.h>
using namespace std;
struct node{
    int key;
};
void deletion(struct node* root){
    root=NULL;
}
void print(struct node* temp){
    if(!temp)
    return;
    cout<<temp->key;
}
int main(){
    struct node* root = new struct node;
    root->key=10;
    cout<<"Initially : ";
    print(root);

    deletion(root);
    cout<<"\nAfter deletion() : ";
    print(root);

    root=NULL;
    cout<<"\nAfter assigning in main() : ";
    print(root);
}

The output I am getting is :

Initially : 10

After deletion() : 10

After assigning in main() :
kuro
  • 2,585
  • 1
  • 12
  • 23

1 Answers1

1

You're passing the pointer by value and modifying that value. To modify the value of a variable being passed, you can either pass it by reference (C++-style) or pass it by pointer(C-style). With C-style, remember to dereference the pointer to change its value for the caller.

C++-style:

void foo(const struct node*& n);

C-style:

 void foo(const struct node** n);
Gabriel
  • 699
  • 4
  • 12