0

I'm on a mission to implement a basic binary tree. Nodes of the tree are structures holding three fields, an integer value and pointers to the left and right children:

typedef struct node {
    int    value;
    struct node *child_left;
    struct node *child_right;
} node;

A new node structure is initialised as:

node node_init(int value, node *child_left, node *child_right) {
    node   k = {value, child_left, child_right};
    return k;
}

A function to store a value inside a left child of the parent node:

int insert_left(node *t, int value) {

    node k = node_init(value, NULL, NULL);

    if (t->child_left == NULL) {
        t->child_left = &k;
    }
    else {
        k.child_left  =  t->child_left;
        t->child_left = &k;
    }
}

A function to print out value of a left child (This is where the problem is):

int node_print(node k) {
    printf("%d", k.child_left->value);
}

Main function to test the basic binary tree:

int main(int argc, char* argv[]) {

    node root  = node_init(7, NULL, NULL);

    insert_left(&root, 3);
    printf("%d\n", root.child_left->value);
    node_print(root);
}

Running this example a direct call to the printf() correctly prints 3 as a value of the left child, but the node_print() outputs a value of the address of the pointer, e.g. -406140704.

This may be a common and ubiquitous problem, but how do I correctly access the value field from inside of the node_print() function? If possible, please direct me to some explanatory reading.

2
  • 4
    node k is a local variable. It is not available anymore once the function returns! Use malloc. Commented Mar 16, 2019 at 12:06
  • 1
    If you are at a level that you are able to implement binary trees, you should know by now that non static local variables are destroyed after the function returns. Commented Mar 16, 2019 at 12:13

1 Answer 1

2

Your init function uses a local variable which is not available anymore once the function returns. Change it to:

node *node_init(int value, node *child_left, node *child_right) {
    node   *k = malloc(sizeof(*k));
    k->value= value;
    k->child_left= child_left;
    k->child_right= child_right;
    return k;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.