📜  使用示例和应用程序引用C++中的指针

📅  最后修改于: 2021-05-30 02:27:21             🧑  作者: Mango

像对简单数据类型的引用一样,我们也可以对指针进行引用。

// CPP program to demonstrate references to pointers.
#include 
using namespace std;
  
int main()
{
    int x = 10;
  
    // ptr1 holds address of x
    int* ptr1 = &x;
  
    // Now ptr2 also holds address of x.
    // But note that pt2 is an alias of ptr1.
    // So if we change any of these two to
    // hold some other address, the other
    // pointer will also change.
    int*& ptr2 = ptr1;
  
    int y = 20;
    ptr2 = &y;
  
    // Below line prints 20, 20, 10, 20
    // Note that ptr1 also starts pointing
    // to y.
    cout << *ptr1 << " " << *ptr2 << " "
         << x << " " << y;
  
    return 0;
}
输出:
20 20 10 20

上面的应用是什么?
考虑以下情况:我们将指针传递给函数,并且希望函数修改指针以使其指向其他对象,并且希望这些更改反映在调用者中。例如,编写一个更改其头部的链表函数,我们将指向指针的引用传递给head,以便该函数可以更改head(另一种方法是返回head)。我们还可以使用双指针来实现相同的目的。

// A C++ program to demonstrate application
// of reference to a pointer.
#include 
using namespace std;
  
// A linked list node
struct Node {
    int data;
    struct Node* next;
};
  
/* Given a reference to pointer to the head of
   a list, insert a new value x at head */
void push(struct Node *&head, int x)
{
    struct Node* new_node = new Node;
    new_node->data = x;
    new_node->next = head;
    head = new_node;
}
  
// This function prints contents of linked
// list starting from head
void printList(struct Node* node)
{
    while (node != NULL) {
        cout << node->data << " ";
        node = node->next;
    }
}
  
/* Driver program to test above functions*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
    push(head, 1);
    push(head, 2);
    push(head, 3);
  
    printList(head);
  
    return 0;
}
输出:
3 2 1
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”