View Code Note:
/*************************************** * ******************* Desc: parameter transfer: the difference between passing a pointer by reference and directly passing a pointer address * Author: Charley * datetime:
* Compiling environment: win7 + vs2008 ************************************* * *********************/# include <iostream> using namespace STD; /* function declaration */void swapbyref (int * &, int * &); void swapbypoi (int *, int *); int main (void) {int I = 10; int J = 20; int * Pi = & I; // point the PI to the memory address where I is located int * PJ = & J; // PJ points to the memory address where J is located. // PASS Parameters by reference. The pointer itself is passed before cout <"swapbyref () is called: pi = "<pI <", * Pi = "<* pI <"; PJ = "<pj <", * PJ = "<* pj <Endl; swapbyref (PI, PJ); cout <" after swapbyref () is called: Pi = "<pI <", * Pi = "<* pI <"; PJ = "<pj <", * PJ = "<* pj <Endl; cout <"**********************" <Endl; // PASS Parameters through pointers, the pointer address is passed before cout <"swapbypoi () is called: Pi =" <pI <", * Pi =" <* pI <"; PJ = "<pj <", * PJ = "<* pj <Endl; swapbypoi (& I, & J); // or directly swapbypoi (PI, PJ); cout <"after swapbypoi () is called: Pi =" <pI <", * Pi =" <* pI <"; PJ = "<pj <", * PJ = "<* pj <Endl; getchar (); Return 0 ;}/ * PASS Parameters by reference: the parameter is an integer pointer reference. The reference is an alias of the pointer. You do not need to allocate space in the memory to receive the parameter reference: swapbyref (Int & V1, Int & V2) */void swapbyref (int * & V1, int * & V2) {int * temp = V1; // assign a value to the pointer. The address executed by the pointer changes to V1 = V2; v2 = temp;}/* pass the parameter through the pointer: the parameter is an integer pointer, and the memory storage needs to allocate space for the shape parameter to receive the passed pointer address. For details, refer to swapbypoi (INT V1, int V2) */void swapbypoi (int * V1, int * V2) {int temp = * V1; // The content pointed to by the Operation pointer, the address of pointer execution is not changed * V1 = * V2; * v2 = temp ;}Execution result:
The result shows that:
1. The swapbyref method directly exchanges the address of the pointer execution of the parameter, so the content pointed to by the pointer is changed.
2. The swapbypoi method is only the content pointed to by the Operation pointer. The address of the pointer execution remains unchanged.