1: Reference passing parameters and pointer passing parameters can achieve the same purpose. Pointer passing parameters also belong to a value pass, which passes a copy of the pointer variable. If you use a pointer reference, you can achieve the purpose of changing the pointer address within the function body. Run the code as follows:
//5.19.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>usingstd::cout;usingStd::endl;Static int Global= -;//Static global Variables voidGetmax (int* &p)//reference to Pointers{ if(*p<Global) { DeleteP//frees memory. p = &Global;//the equivalent of PI1 's reference changed. }} voidGetmin (int*p) { if(*p>Global) { DeleteP//freed up the memory that pI2 points top = &Global;//copy value changed, pI2 no change }}intMain () {int* PI1 =New int;//dynamically assign an address int* PI2 =New int; cout<<"pI1 point to Address:"<<pI1<<Endl; cout<<"pI2 point to Address:"<<pI2<<Endl; *PI1 = the;//Global Larger*pi2 = -;//Global Smallercout<<"global variable Address:"<<&Global<<Endl; cout<<"bring pI1 and pI2 into the Getmax and getmin functions respectively"<<Endl; Getmax (pI1); Getmin (pI2); cout<<"pI1 point to Address:"<<pI1<<Endl; cout<<"pI2 point to Address:"<<pI2<<Endl; cout<<"value of *pi1:"<<*pI1<<Endl; cout<<"value of *pi2:"<<*pI2<<Endl; return 0;}/*The Getmax function changes the address of the pointer by passing a reference to the pointer, and the address of the pointer pI1 finally points to the global variable. The Getmin function, which passes pointers by value, can only change the contents of memory, and performing operations on memory does not change the address pointed to by the pointer. */
View Code
Operation Result:
Introduction to C + + Classic-Example 5.19-reference and passing parameters of pointers