What is the difference between pointer assignment methods?

Thanks for watching my question. I just ran into a really fundamental problem when I implement BST, that is, "what's the difference in different approaches for assigning a pointer?" We all know that point assignment can use:

int *p, q; p = &q; 

Or:

 int *p, *q; p = q; 

They must be the same. But in my case below they work in a completely different way:

 template <typename T> void Tree<T>::_insert(TreeNode<T>*& tree, const T& value, const unsigned& key) { // TreeNode<T> node(value, key); // if(tree == nullptr) tree = &node; TreeNode<T> *node = new TreeNode<T>(value, key); if(tree == nullptr) tree = node; else if(key < tree->index) _insert(tree->left, value, key); else if(key > tree->index) _insert(tree->right, value, key); else if(key == tree->index) std::cerr << "_insert: repeating key" << std::endl; } 

Using the first method (marked), the function will not assign a tree equal to node, while the second method works fine.

So, is this my mistake, or are they naturally different?

+6
source share
3 answers

Pay attention to the first case:

 // TreeNode<T> node(value, key); // if(tree == nullptr) tree = &node; 

node is an object pushed onto the stack .

While in the second case

 TreeNode<T> *node = new TreeNode<T>(value, key); if(tree == nullptr) tree = node; 

node stands out on the heap .

The difference is that the _insert function _insert returned, its stack stack is set, and all local variables / objects become invalid, as a result you will have errors in memory.

+3
source

No, the two methods should not be the same:

  • The first assignment p = &q works fine because q is the actual object in memory and p is a pointer to it
  • The second assignment p = q assigns a unified pointer q to p , which is undefined.

This is why the two implementations are different.

If you want to assign q to p , you must first assign q . For example, you can assign it a new int :

 int *p, *q = new int; p = q; 

However, in this case, you can also assign new int directly to p .

+3
source
 int *p, q; p = &q; 

This means that p now has an address in which the integer q is stored in memory.

 int *p, *q; p = q; 

In this, you copy the address stored in the q pointer to p.

0
source

All Articles