Example 1:
[Cpp]
# Include <stdio. h>
Int f (int * p ){
P = p + 1;
Return printf ("% d \ n", * p );
}
Void main (){
Int a [] = {1, 2 };
Int * p = a; // the pointer p is the first address.
F (p); // call
Printf ("% d", * p); // The value of p will not change.
}
Result:
2
1
Press any key to continue
Example 2:
[Cpp]
# Include <stdio. h>
Void z (int * p ){
P = p + 1;
* P = 100;
}
Void mian (){
Int a [] = {1, 2 };
Int * p =;
Z (p); // call
Printf ("a [1] = % d", * (p + 1); // the value in the memory space pointed to by the pointer (p + 1) has changed
}
Result:
A [1] = 100
Press any key to continue
Through the above two examples, we can conclude that when a pointer is passed as a parameter, its value cannot be changed in other functions (the address pointed by this pointer), but it can be changed.
The value in the address.
So to realize the value exchange between the two first-level pointers, we need to use the second-level pointer: (pointer q points to a, pointer p points to B, implement q points to B, p points to)
[Cpp]
# Include <stdio. h>
Void exchange (int ** x, int ** y ){
Int * temp;
Temp = * x; // * x = * qq = &
* X = * y;
* Y = temp;
}
Void main (){
Int a = 100;
Int B = 12;
// Define the pointer
Int * q = &;
Int * p = & B;
Int ** qq = & q;
Int ** pp = & p;
// Output
Printf ("q = % p \ n", q );
Printf ("p = % p \ n", p );
// Call the function for conversion
Exchange (qq, pp );
Printf ("========= changed ===============\ n ");
Printf ("q = % p \ n", q );
Printf ("p = % p \ n", p );
}
Result:
Q = 0012FF44
P = 0012FF40
========= After the change ==========
Q = 0012FF40
P = 0012FF44
Press any key to continue
From like7xiaoben