user3450947
user3450947

Reputation: 67

The pointer in C

There is some my code. I have a problem.

include "binarytree.h"

int insert2( int num, binarytree** root)
{   
    if ( *root ==  NULL )
    {
        *root = setnode( num, NULL);
        if ( *root == NULL )
            return 1;
        else
            return 0;
    }
    binarytree *temp , *p;
    temp = *root;
    while ( temp !=  NULL ) 
    {   
        //p = temp;
        if ( num < temp->key )
        {
            temp = temp->left;
            if ( temp == NULL )
                printf( "temp = NULL");
        }
        else if ( num > temp->key)
             temp = temp->right;
    }
    if ( num < temp->key )
        temp->left = setnode( num, temp);
    else temp->right = setnode( num, temp);
    return 0;
}

I don't know why there after some iterations "temp = NULL" is printed , but in while temp != NULL is true!? How???

while ( temp !=  NULL ) 
        {   
            //p = temp;
            if ( num < temp->key )
            {
                temp = temp->left;
                if ( temp == NULL )
                    printf( "temp = NULL");
            }
            else if ( num > temp->key)
                 temp = temp->right;
        }

Upvotes: 1

Views: 103

Answers (1)

erik258
erik258

Reputation: 16304

Becuase you change temp within the while loop. Remember, a while expression is tested before every iteration.

We can only assume from your code that temp->left is null.

Upvotes: 3

Related Questions