1
void extract_left_subtree(node *right_child)
{
    while(right_child->right)
    {
        right_child = right_child->right;
    }  
    printf("rightmost inside the funtion is %d\n",right_child->data);
}

in this function the last line is printing the correct value.

 node *right_child=root;
 extract_left_subtree(right_child);
 printf("rightmost child is %d\n",right_child->data);

But here I'm getting some garbage value.

I know what the problem is, I know why it's happening, the only thing I don't know is how to rectify this? There are keywords like ref and out in C# which can be used to achieve the same but the issue is, how can we do the same in C language?

I don't want to return values from the method please

Piyush Kumar
  • 191
  • 1
  • 10
  • Re "*I don't want to return values from the method*", C doesn't have classes, so it doesn't have methods. The above is a *function* (C's name for it) or *subroutine* (generic name for it). – ikegami Jan 05 '20 at 07:54

1 Answers1

4

I don't want to return values from the method please

If you don't want to return a value you can do:

void extract_left_subtree(node **right_child)
{
    while((*right_child)->right)
    {
        (*right_child) = (*right_child)->right;
    }  
    printf("rightmost inside the funtion is %d\n", (*right_child)->data);
}

and call it like:

extract_left_subtree(&right_child);

This passes the address of right_child to the function and then the function can directly update the value of right_child

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • Instead of using the same parameter as input and as output, an alternative would be to rewrite the function to use two parameters, one parameter for input and one for output. – Andreas Wenzel Jan 05 '20 at 07:49
  • 1
    @AndreasWenzel why would you want to do that? Calling a function like `extract_left_subtree(right_child, &right_child);` would just look strange, IMO – Support Ukraine Jan 05 '20 at 07:59
  • This worked like a charm, I totally forgot that pointers also stay in the memory and they also have some address. – Piyush Kumar Jan 05 '20 at 07:59