As far as I understood I think that when we pass a pointer to a function as its parameter, the operations performed by the function on that pointer parameter are directly done in the memory address where the pointer is pointing to.
But I'm not able to understand why this is not happening in the following code.
It seems the function is accepting the pointer parameter, then creating its own copy of the parameter, making all the changes in the local copy, and when it finishes the changes are lost.
I was learning about Binary Search Trees and implemented the BST myself before referring to how the instructor has done it. So I wrote the following code.
#include <stdio.h>
#include <stdlib.h>
typedef struct bstNode {
struct bstNode* left;
int data;
struct bstNode* right;
} bstNode_t;
bstNode_t* root = NULL;
bstNode_t* getNewNode(int data) {
bstNode_t* newNode = (bstNode_t*)malloc(sizeof(bstNode_t));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
bstNode_t* insert(bstNode_t* root, int data) {
if (root == NULL) {
root = getNewNode(data); return root;
} else if (data <= root->data) {
root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);
}
return root;
}
int search(bstNode_t* root, int item) {
if (root == NULL) {
return 0;
} else if (item == root->data) {
return 1;
} else if (item <= root->data) {
return search(root->left, item);
} else {
return search(root->right, item);
}
}
int main() {
insert(root, 20); insert(root, 10); insert(root, 30); printf("%d\n", search(root, 10)); printf("%d\n", search(root, 20)); printf("%d\n", search(root, 30)); printf("%d\n", search(root, 40));
return 0;
}
But when I referred to the Instructors code everything is still the same the only change is in the main() function as below.
int main() {
root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); printf("%d\n", search(root, 10)); printf("%d\n", search(root, 20)); printf("%d\n", search(root, 30)); printf("%d\n", search(root, 40));
return 0;
}
Now it seems confusing to me. Why do we have to save the returned address from the insert() method again when we already defined root as a global variable and also assigned the returned address to root in the insert() method already.
This is giving me an impression that in the insert() function when we write
root = getNewNode(data);
the function insert() creates a local copy of root and makes the changes in that local copy.
Totally confused. Can someone please explain to me, what is happening?
What I have tried:
I tried to debug the code to see what is happening internally and it seems that the root pointer is correctly attached to the pointer returned by insert() method until insert() is called again. As when it is called again it makes root() as NULL and starts from the if() statement where if(root==NULL) and the process repeats and I get all wrong output.