c++ - Working with pointer to pointer -
i have binarysearchtree struct:
struct bstnode { int value; bstnode *left = nullptr; bstnode *right = nullptr; }; struct bst { bstnode *root = nullptr; };
and functions work tree:
bstnode **findposition(bstnode *node, int value) { if (value < node->value) { if (node->left) { return findposition(node->left, value); } else { return &node->left; } } if (value > node->value) { if (node->right) { return findposition(node->right, value); } else { return &node->right; } } return &node; } void remove(bstnode** position, int value) { if ((*position)->left == nullptr && (*position)->right == nullptr) { delete (*position); *position= nullptr; } } void remove(bst &bst, int value) { bstnode **position = findposition(bst.root, value); if (*position != nullptr) { remove(position,value); } } void add(bstnode *node, int value) { bstnode **position = findposition(node, value); bstnode *newnode = new bstnode; newnode->value = value; *position = newnode; } void add(bst &bst, int value) { if (!bst.root) { bstnode *root = new bstnode; root->value = value; bst.root = root; } else { add(bst.root, value); } }
adding works fine, removing elements work strangely (now should work leaf nodes). sets value of node zero. think problem in use of pointers.
what doing wrong?
your final case return &node;
in findposition
wrong. returns garbage.
if changed signature bstnode **findposition(bstnode *&node, int value)
then in many uses fix final return. haven't (or depending on have vs. posted can't) check uses see if covers every way use findposition.
without changing signature, returning address of parameter of call, invalid time returned value used. signature change, same return instruction return correct address. but signature change represents significant change contract between findposition , callers, works if change ok callers. otherwise, need bigger change. no change findposition work without changing contract callers.
edit (because of comment). in final return instruction need return original address of pointer. without signature change returning address of copy of pointer. signature change, syntax of function still treats node
pointer, there level of indirection hidden inside semantics. level of indirection, original address of pointer available (and computed &node
) rather address of copy.
also (building on answer dasblinkenlight) test null pointer needed in many places version, error prone. if push test top of findposition needed in fewer places , more robust:
bstnode **findposition(bstnode *&node, int value) { if ( node ) { if (value < node->value) { return findposition(node->left, value); } if (value > node->value) { return findposition(node->right, value); } } return &node; }
Comments
Post a Comment