When pointers and arrays are passed into functions as arguments, the incoming address, which points to the address of the variable and the first address of the group, can change the value of the pointer or array in the function, but in essence they are the passing of the value (which is passed by the value of the variable, which does not change the original value of the argument). , we cannot operate on pointers and array addresses (e.g., address assignment, allocating memory, etc.), and you need to use pointer references or pointers to address operations.
Example:
<span style= "FONT-SIZE:18PX;" >int Main ()
{
int i = 1;
int *p = &i;
int sz[] = {1};
Testfun (P, SZ);
testFun1 (p);
testFun2 (p);
int * P1 = NULL;
TestFun3 (p1);
*P1 = ten; A
delete p1;
return 0;
} </span>
<span style= "FONT-SIZE:18PX;" >//value passes
void testfun (int *p, int sz[])
{
*p = ten;
Sz[0] =;
}
The value is passed
int g_int = m;
void testFun1 (int *p)
{
p = &g_int;
}
Pointer reference
void testFun2 (int *&p)
{
p = &g_int;
}
Pointer reference allocates memory
void testFun3 (int *&p)
{
p = new int;
} </span>
After running Testfun (), the pointer value becomes 10 and the array becomes 20
After running TestFun1 (), the pointer value is 10, unchanged
After running TestFun2 (), using a pointer reference, the pointer value changes to 50
After running TestFun3 (), using a pointer reference, the memory allocation is successful and the pointer can be assigned
Pointer reference = = Pointer to pointer
The reference to the pointer holds the address of the pointer itself (that is, a 4-byte space similar to int), address assignment or memory allocation to it, in effect, is to cause the pointer to point back to the first address of a new block of memory (that is, save the new pointer variable address, of course, the same type).
Use the const & Pass argument
is a value pass, and although the reference is used, the address is passed in, but the value passed in cannot be changed.