C++中指针的引用及其应用实例

喜欢 推荐人 对于简单的数据类型,我们可以参考 指针 .

null

// CPP program to demonstrate references to pointers.
#include <iostream>
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

上面的应用是什么? 考虑一个情况,我们传递一个函数的指针,我们希望函数修改指针指向其他东西,并且我们希望这些更改在调用方中反映。例如,编写一个链表函数来改变它的头,我们将引用传递给指向头的指针,以便该函数可以改变头(另一种方法是返回头)。我们也可以通过使用 双指针 .

// A C++ program to demonstrate application
// of reference to a pointer.
#include <iostream>
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

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享