mabalenk
mabalenk

Reputation: 1043

Recursive structure (binary tree): obtain values via struct pointer from inside function

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.

Upvotes: 0

Views: 47

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

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;
}

Upvotes: 2

Related Questions