tags:

views:

141

answers:

3
void Insert(AVLnode * & root, string X)
{
    if ( root == NULL)
    {
     root = GetNode(X);
    }
    else if ( root->info > X )
    {
     Insert(root->left,X);
     if ( height(root->left) - height(root->right) == 2 )
      if ( X < root->left->info )
       RotateRR(root);
      else
       RotateLR(root);
    }
    else if ( root->info < X )
    {
     Insert(root->right,X);
     if ( height(root->right) - height(root->left) == 2 )
      if ( X > root->right->info )
       RotateRR(root);
      else
       RotateLR(root);
    }
    root->height = max( height(root->left), height(root->right) )+1;
}
AVLnode* find(AVLnode* root,string X)
{
    if (!root) return 0;
    if ( root->info == X )
     return root;
    else if (root->info < X)
     find(root->left,X);
    else if (root->info > X)
     find(root->right,X);
    return 0; 
}
int main(int argc,char* argv)
{
    AVLnode* Dic;
    Insert(Dic,"adf");
    return 0;
}

The first time in Insert, root is NULL but when I debug, it skips root == null. What's going on?

+2  A: 

The problem is in the AVLnode* Dic; statement of main(). You are sending an uninitialized pointer to insert() from main(). It contains garbage values. Initialize it to NULL

Naveen
Thanks, simple and useful answer :)
nXqd
+1  A: 

The first time it's not NULL. Variables do not auto-initialize to NULL or 0 in C++; they contain garbage (whatever the memory address they occupy contained before).

Replace AVLnode* Dic; with AVLnode* Dic = NULL; and try again.

Andreas Bonini
+1  A: 

"The first time in Insert", in the code you give, root is a "random"-ish value, because you never initialize Dic -- so it may well happen to be NULL when you're running without a debugger and otherwise if you are using a debugger. That's just a definite bug in your code, so add = 0 before the ; in the first line of main's body. After which, you may find more bugs (hard to say, since you don't show us GetNode or the Rotate thingies, even though you do show us the find function that's never ever called -- peculiar choice of code to show us, indeed).

Alex Martelli