0

So I did already manage to solve my problem but I have trouble understanding what exactly was the problem. My code before was:

BinaryTree removePrivate(int x, BinaryTree *node)
{
    if ((*node).m_key < x)
        *(*node).m_right = removePrivate(x, (*node).m_right);
    else if ((*node).m_key > x)
        *(*node).m_left = removePrivate(x, (*node).m_left);
    else
        node= NULL ;
    return *node;
}

It compiles just fine but things go to hell when it gets called. Access violation at return *node;

I have changed it to:

[*]= * has been added, [ ]= * has been removed

BinaryTree [*]removePrivate(int x, BinaryTree *node)
{
    if ((*node).m_key < x)
        [ ](*node).m_right = removePrivate(x, (*node).m_right);
    else if ((*node).m_key > x)
        [ ](*node).m_left = removePrivate(x, (*node).m_left);
    else
        node= NULL ;
    return [ ]node;
}

Now everything works just fine but I am really not 100% sure why this is better.

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
Bubibob
  • 191
  • 1
  • 13
  • 1
    As a service to the readers you might want to point out which lines differ exactly how. – René Nyffenegger May 08 '16 at 17:13
  • 1
    In your old code, dereferencing a null pointer as you do with your `node` when it is `NULL` has undefined behaviour since you cannot dereference nothing. – Jonathon Ogden May 08 '16 at 17:17
  • 2
    Try to use `node->m_right` instead of `(*node).m_right` if possible it's more readable [why?](http://stackoverflow.com/questions/4263796/c-pointer-dereference-operator-vs). Please also correct your spelling in this post. – Foto Blysk May 08 '16 at 17:29

1 Answers1

2

When you write (*node), you are dereferencing the pointer node. If you use *(*node), as you originally had, you are dereferencing (*node), which is the dereferenced node. Thus, you are dereferencing twice, which does not make sense because node because points to a BinaryTree object, not another pointer.

In a simpler form:

*node = dereference node
*(*node) = dereference *node = dereference node twice
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94