PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] why does there is no update in Node *root?

 July 06, 2022     binary-search-tree, c, pass-by-reference, struct     No comments   

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:

  1. 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);
    
  2. 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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing