Note that there are some explanatory texts on larger screens.

plurals
  1. POCall by value vs call by reference while dealing with binary tree
    primarykey
    data
    text
    <p>When we want to change the value of an ordinary variable by in a function we pass it using call by reference. But I am not able to understand the intricacies when we have to pass a pointer variable(like a node of a binary tree) using call by refence. I understand that if we want to modify the poiter variable to point to another node we have to use call by reference. But what if we have to modify the data element of the root. I thought that to change it also we would need a call by reference. But the following code snippet is giving an output of 10, 10, 10 even though I have passed the root node of the tree using call by value in the function modifyTree. Am I missing something over here?</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; struct node { int data; struct node* left; struct node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node-&gt;data = data; node-&gt;left = NULL; node-&gt;right = NULL; return(node); } /* This function sets the data fields of some of the nodes of tree to 10*/ void modifyTree(struct node* node) { node-&gt;data = 10; node-&gt;left-&gt;data = 10; node-&gt;right-&gt;data = 10; } int main() { struct node *root = newNode(1); root-&gt;left = newNode(2); root-&gt;right = newNode(3); root-&gt;left-&gt;left = newNode(4); root-&gt;left-&gt;right = newNode(5); modifyTree(root); printf("%d\n", root-&gt;data); printf("%d\n", root-&gt;left-&gt;data); printf("%d\n", root-&gt;right-&gt;data); getchar(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload