Reputation: 3
I don't know what's causing the program to fail, other than the fact that it has something to do with trying to assign the left and right children some pointer. There is no error message, the program just fails to run. I just assume it's because I'm assigning the pointers incorrectly.
Here's the struct:
struct TreeNode
{
Type nodeinfo;
BinaryTree<Type> *left;
BinaryTree<Type> *right;
};
The class's name is BinaryTree using a template. Here's the offending method:
template <typename Type>
void BinaryTree<Type>::setSubtree(Type a){
root = new TreeNode;
BinaryTree<Type> *b,*c;
root->nodeinfo=a;
b->root = s.top();
root->right = b;
s.pop();
c->root = s.top();
root->left = c;
s.pop();
s.push(root);
}
s is a stack of type TreeNode* and holds the nodes. root is the individual nodes.
I've changed it so many times, I've forgotten what I started with. This is the test code (setInfo works just fine):
tree.setInfo('b');
tree.setInfo('c');
tree.setSubtree('-');
Any insight as to how I'm supposed to assign the pointers would be greatly appreciated.
Upvotes: 0
Views: 83
Reputation: 33116
BinaryTree<Type> *b,*c;
...
b->root = s.top();
...
c->root = s.top();
You are never initializing the pointers b
and c
.
You should have caught these errors yourself. Coming to this site as your first defense against errors is a very bad idea. You won't learn how to debug. How could you have discovered these problems without our help? With your compiler, with an analysis tool such as valgrind, with your debugger, or even by hand execution of your code.
Learn how to use your compiler to your advantage by enabling compiler warnings. GNU and clang will catch errors like these when compiled optimized and with adequate warnings enabled. Learn how to use a debugger. Learn how to hand execute code.
Upvotes: 0