j.Doe
j.Doe

Reputation: 212

Dereferencing double pointer to pass to recursive function

I have the following recursive function which is supposed to call itself passing a pointer by reference. How can I dereference tmproot->left and tmproot->right so that I can pass it to tree_input()?

typedef struct node_s {

    int value;
    struct node_s *left;
    struct node_s *right;

} node_t;

node_t new_node() {
    node_t *new_node = (node_t*)malloc(sizeof(node_t));
    new_node->left = NULL;
    new_node->right = NULL;
    return *new_node;
}

void tree_input(int value, node_t **tmproot)
{
    if (*tmproot == nullptr) {
        node_t *node = &new_node();
        node->value = value;
    }
    else if (value < (*tmproot)->value) {
        tree_input(value, tmproot->left);
    }
    else if (value >= value) {
        tree_input(value, tmproot->right);
    }
    return;
}

tree_input() is called the first time using tree_input(new_value, &root); I am sure I am missing a simple trick.

Upvotes: 1

Views: 770

Answers (1)

user4442671
user4442671

Reputation:

To answer the question as asked:

void tree_input() takes a pointer to a pointer as an argument, and node_s->left is a pointer. So all you have to do is get a pointer to the pointer by using the address-of operand.

However, since tmproot is a pointer-to-pointer, it also needs to be dereferenced once before you can use the -> operator.

tree_input(value, &(*tmproot)->left);

However, you should also know that your new_node() function, and how you use it, is pretty broken.

The way it's setup now, you create a new node_t on the heap, copy it on the stack, and store a pointer to that stack instance in your tree, which immediately becomes a dangling pointer, while the heap-allocated memory just leaks away.

To fix it, the function should return a node_t*, not a node_t. Everything else should flow naturaly from there.

Upvotes: 3

Related Questions