In c/c ++, a function can transmit parameters in three forms: value, reference, and pointer. The following three forms are introduced respectively. If you need them, please refer to them.
Next let's look at a piece of code to see the results produced by the three transfer methods.
Copy codeThe Code is as follows:
# Include <cstdlib>
# Include <iostream>
Using namespace std;
Void change1 (int n)
{
Cout <"value transfer-function operation address" <& n <endl;
N ++;
}
Void change2 (int & n)
{
Cout <"reference transfer -- function operation address:" <& n <endl;
N ++;
}
Void change3 (int * n)
{
Cout <"pointer passing-function operation address" <n <endl;
* N = * n + 1;
}
Int main (int argc)
{
Int n = 10;
Cout <"real parameter address:" <& n <endl;
Cout <"original value n =" <n <endl;
Change1 (n );
Cout <"afterchange1 n =" <n <endl;
Change2 (n );
Cout <"afterchange2 n =" <n <endl;
Change3 (& n );
Cout <"afterchange3 n =" <n <endl;
System ("PAUSE ");
Return EXIT_SUCCESS;
}
The output is as follows:
It can be seen that the change1 function does not change the value of the real parameter n whose original value is 10, while the change2 and change3 functions have successfully changed its value.
At the same time, you can view the operation address of the function and find that the Operation address of change1 is not the address of the real parameter n.
Note:
1. The value transfer form does not pass n itself, so the value of n cannot be changed.
2. In fact, the address is passed in, and the address can be operated successfully.
Note:
1. Initialization is required before reference and pointer passing.
2. The storage units opened by the reference and pointer in the memory should be valid units and should not be NULL.
3. Once the reference is initialized, the reference relationship cannot be changed, and the pointer can change the object to which it points.
If no pointer is initialized or referenced, let's look at an example:
Copy codeThe Code is as follows:
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <iostream>
Using namespace std;
Void init (char * p)
{
P = (char *) malloc (100 );
Cout <"pointer passing-function operation address" <p <endl;
}
Int main ()
{
Char * p = NULL;
Cout <"original real parameter address" <p <endl;
Init (p );
If (p)
{
Strcpy (p, "hello ");
Printf ("% s n", p );
}
Else
{
Printf ("% s", "p not init n ");
}
Free (p );
System ("PAUSE ");
Return EXIT_SUCCESS;
}
Output result: