0

The 't' pointer in the insert() function is set to NULL every time I call the insert function. Is it something to do with messing up of pointers?

    int main() {
    int num, i;
    tree *t;
    t = NULL;
    for(i = 0; i < 5; i++) {
        scanf("%d", &num);
        insert(t, num);
    }
    //inorder(t);
    return 0;
}

The insert function is as follows:

    void insert(tree *t, int num) {
        int flag;
        tree *p, *q;
        tree *temp = (tree *)malloc(sizeof(tree));
        temp->data = num;
        temp->left = NULL;
        temp->right = NULL;

        if(t == NULL) {
            t = temp;
            printf("Hello");
            return; 
        }
        printf("%d", t->data);
        p = t;
        while(p) {
            q = p;
            if(p->data <= num) {
                p = p->right;
                flag = 1;
            }   
            else {
                p = p->left;
                flag = 0;
            }   
        if(flag == 1)
            q->right = temp;
        else
            q->left = temp; 

        }
    }

My tree structure is as follows :

    typedef struct tree {
            int data;
            struct tree *left, *right;
        }tree;
  • 2
    Please provide a [Minimal Complete Verifiable Example](http://stackoverflow.com/help/mcve) . I would venture to guess someone who calls insert is passing a NULL pointer. Someone might also bring up [casting the return type of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Michael Petch Oct 10 '15 at 18:46
  • @MichaelPetch, Will this edit be sufficient? And actually this was my first question on stack overflow...So sorry for incomplete code. – Bruce Wayne Oct 10 '15 at 18:59
  • 1
    If you intend to change the address `t` in your function _insert_ you are going to have to pass the address of the `t` pointer. `void insert(tree *t, int num)` would become `void insert(tree **t, int num)` and then deference it (`t = temp;` would become `*t = temp;` – Michael Petch Oct 10 '15 at 19:07
  • you'd of course have to to similar dereferencing for each access to `t` – Michael Petch Oct 10 '15 at 19:13
  • This [Stackoverflow answer](http://stackoverflow.com/a/12308866/3857942) may provide some useful information. Wherever it mentions a pointer to double, it would apply to any pointer (like a pointer to `tree`) – Michael Petch Oct 10 '15 at 19:16
  • @MichaelPetch, Thanks. Works perfectly now! – Bruce Wayne Oct 11 '15 at 05:38

0 Answers0