Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning structure pointer

Tags:

c

I'm confused with code below:

struct node* newNode(int data) 
{
  struct node* node = (struct node*)
                       malloc(sizeof(struct node));
  node->data  = data;
  node->left  = NULL;
  node->right = NULL;

  return(node);
}

struct node* insert(struct node* node, int data) 
{
  /* 1. If the tree is empty, return a new,     
      single node */
  if (node == NULL) 
    return(newNode(data));  
  else
  {
    /* 2. Otherwise, recur down the tree */
    if (data <= node->data) 
        node->left  = insert(node->left, data);
    else
        node->right = insert(node->right, data);

    /* return the (unchanged) node pointer */
    return node; 
  }
}

newNode returns a pointer to the structure it has allocated. However in line 6 of the insert function the return value of newNode is not being assigned to anything, it's just being called. How is the code further down able to use the newly created node structure?

like image 687
Tony54 Avatar asked Feb 03 '26 03:02

Tony54


1 Answers

Code below will run, if the tree is NOT empty. So, when the code in step .2 runs, the code in step .1 does not.

When the recursion unwinds, you can see that the assign operation is happening, for example:

node->left  = insert(node->left, data);

Oh and as ThunderWiring said, do not cast malloc!

like image 91
gsamaras Avatar answered Feb 05 '26 01:02

gsamaras