What is Node *& aNode? [duplicate]

寵の児 提交于 2019-12-13 19:50:58

问题


In the following code:

void insert(Node *& aNode, int x) {
  if (!aNode) {
    aNode = new Node(x);
    aNode->next = aNode;
    return;
  }

  Node *p = aNode;
  Node *prev = NULL;
  do {
    prev = p;
    p = p->next;
    if (x <= p->data && x >= prev->data) break;   // For case 1)
    if ((prev->data > p->data) && (x < p->data || x > prev->data)) break; // For case 2)
  } while (p != aNode);   // when back to starting point, then stop. For case 3)

  Node *newNode = new Node(x);
  newNode->next = p;
  prev->next = newNode;
}

What is Node *& aNode?

How should I use this function, I mean, which type of parameter should I pass?


回答1:


I think this code is C++, not C, and Node *&aNode is a reference to a pointer to a Node, so you would pass a Node* to the function, and function would make a reference to that (so the memory location your Node* is pointing to can change).

You may find the Wikipedia article on References (C++) interesting.

A simple example:

#include <iostream>
void addOneToValue(int num) {
    ++num;
}

void addOneToRef(int &num) {
   ++num;
}

int main() {
   int num = 0;

   // print 0
   std::cout << num << std::endl;

   // print 0 again (addOneToValue() has no effect)
   addOneToValue(num);
   std::cout << num << std::endl;

   // print 1 (addOneToRef() changes the value of num)
   addOneToRef(num);
   std::cout << num << std::endl;
}

@crashmstr's comment reminded me that I should say how they're different from pointers. Wikipedia does a better job that I could though:

  • It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
  • Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
  • References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
  • References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.
  • Most compilers will support a null reference without much complaint, crashing only if you try to use the reference in some way.


来源:https://stackoverflow.com/questions/7906546/what-is-node-anode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!