Issue
This is a very simple example for inserting a number.
typedef struct node {
int data;
struct node *left, *right;
} node;
node * newNode(int val) {
node* n = malloc(sizeof(node));
n->data=val;
n->left=NULL;
n->right=NULL;
return n; }
void insert(node* node, int key) {
if (node == NULL)
node = newNode(key);
}
int main() {
node *root = NULL;
insert(root, 5);
printf("%d\n", root->data);
return 0;
}
The problem is, Why does the printf
print nothing when I insert 5 in root
?
Solution
In C all arguments are passed by value. That means the value is copied into the argument variable, and when you do the assignment node = newNode(key);
you only assign to the local node
variable.
There are two solutions to this problem:
Return the new node instead:
node* insert(node* the_node, int key) { if (the_node == NULL) the_node = newNode(key); return the_node; } ... root = insert(root, 5);
Emulate pass by reference, which can be done by passing a pointer to the variable using the address-of operator
&
:void insert(node** the_node, int key) { if (*the_node == NULL) *the_node = newNode(key); } ... insert(&root, 5);
Answered By - Some programmer dude Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.