Answer the question
In order to leave comments, you need to log in
Why is an infinite pointer created in the tree?
I'm trying to read from a binary file into a search tree. But at one point, where there should be a null pointer, for some reason, an infinite pointer to itself appears. For a long time I searched for the cause with a debugger, but I did not find it. Maybe a side view would help?
struct Tree
{
Tree* left = 0;
Tree* right = 0;
int key;
int size = 1;
string brand;
string name;
};
Tree* insert(Tree* tree, int key, string brand, string name)
{
if (!tree) {
Tree* newtree = new Tree();
newtree->key = key;
newtree->brand = brand;
newtree->name = name;
return newtree;
}
if (tree->key > key)
tree->left = insert(tree->left, key, brand, name);
else
tree->right = insert(tree->right, key, brand, name);
return tree;
}
Tree * readElement(Tree* tree) {
string brand;
string name;
int carNumber;
int len;
char* buf;
int left, right;
iffile.read((char*)&carNumber, 4);
iffile.read((char*)&len, 4);
buf = new char[len];
iffile.read(buf, len);
brand = buf;
delete[]buf;
iffile.read((char*)&len, 4);
buf = new char[len];
iffile.read(buf, len);
name = buf;
delete[]buf;
tree = insert(tree, carNumber, brand, name);
iffile.read((char*)&left, 4);
if (left) {
tree->left = readElement(tree);
}
else {
tree->left = 0;
}
iffile.read((char*)&right, 4);
if (right) {
tree->right = readElement(tree);
}
else {
tree->right = 0;
}
return tree;
}
Tree* readFromFile(Tree* tree) {
iffile.open(filePath, ios::binary | ios::in);
tree = readElement(tree);
iffile.close();
return tree;
}
Answer the question
In order to leave comments, you need to log in
This code creates a circular link:
if (left) {
tree->left = readElement(tree);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question