C
C
CodeInside2016-11-12 13:00:29
C++ / C#
CodeInside, 2016-11-12 13:00:29

Why, after converting a branch to a binary tree, does it immediately disappear?

There is a binary tree, which is an English-Russian dictionary. In one method, I need to convert a branch to a tree.

struct Elem
{
  char eng[15]; // ключ
  char rus[15]; // значение
  Elem *left, *right, *parent;
};
Tree::Tree(Elem* node)
{
  Copy(node, root);
}

void Tree::Copy(const Elem* from, Elem* to)
{
  if (from == nullptr)
  {
    to = nullptr;
    return;
  }
  
  to = new Elem;
  strcpy_s(to->eng, 15, from->eng);
  strcpy_s(to->rus, 15, from->rus);

  cout << from->eng << '\t' << to->eng << endl;
  Copy(from->left, to->left);
  Copy(from->right, to->right);
}

Examination:
Tree obj;
  Insert(obj);
  Tree obj2(obj.GetRoot());
  cout << obj2.GetRoot();
  _getch();

So obj2.GetRoot() returns nullptr. I go through the debugger - everything is fine. Each node is correctly copied to the right place, but after this conversion constructor (if you can call it that), root immediately becomes nullptr. Can you help to catch this bug?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2016-11-12
@CodeInside

Here you create a new Elem in a local variable 'to'
to = new Elem;
After the function exits, this pointer is lost, and the original root is not changed.
Try passing a pointer by reference like this
void Tree::Copy(const Elem* from, Elem* &to)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question