Four pointer-related questions in the C language, and four pointers in the middle
Example 1.
Void fun (int * x, int * y ){
Printf ("% d, % d", * x, * y );
* X = 3;
* Y = 4;
}
Main ()
{
Int x = 1, y = 2
Fun (& y, & x );
Printf ("% d, % d", x, y );
}
Result
2, 1
4, 3
Note that when calling the fun function main, y and x are intentionally reversed.
--------------------------------------------------------------
Example 2.
# Include <stdio. h>
Void swap (int * p1, int * p2)
{
Int temp;
Temp = * p1;
* P1 = * p2;
* P2 = temp;
}
Main ()
{
Int a, B;
Int * p1 = & a, * p2 = & B;
Scanf (% d, p1, p2 );
Swap (p1, p2 );
Prinf ("% d, % d", * p1, * p2 );
}
If you enter2 and 5
The output result is
5, 2
Cause: the title is used when the swap function is called. Therefore, modifying the content value referenced by p1 and p2 in the swap function will affect the values of a and B outside.
--------------------------------------------------------------
Example 3:
# Include <stdio. h>
Void swap (int * p1, int * p2)
{
Int * temp;
Temp = p1;
P1 = p2;
P2 = temp;
}
Main ()
{
Int a, B;
Int * p1 = & a, * p2 = & B;
Scanf (% d, p1, p2 );
Swap (p1, p2 );
Prinf ("% d, % d", * p1, * p2 );
}
Different from 2, temp in the swap function is a pointer. temp = p1 points temp to 2, p1 = p2 points p1 to 5, and p2 = temp points p2 to 5.
However, the final result is still
2, 5
The reason is: although the pointer is passed when the swap function is called in main, all operations in the swap function are: Modify the pointer itself, instead of using the * operator again to modify the "content value pointed to by the pointer"
---------------------------------------------------------------------
Example 4:
# Include <stdio. h>
Void swap (int * p1, int * p2)
{
Int * temp;
* Temp = * p1;
* P1 = * p2;
* P2 = * temp;
}
Main ()
{
Int a, B;
Int * p1 = & a, * p2 = & B;
Scanf (% d, p1, p2 );
Swap (p1, p2 );
Prinf ("% d, % d", * p1, * p2 );
}
Similar to 2. The only difference is that temp is defined as a pointer rather than a common variable. It seems like the output result of 2 is still
2, 5.
However, the compiler reports an error: Invalid Memory write.
The reason is: temp is a wild pointer and there is no reservation pointing to it. If it points to the system zone, the operating system may crash.
If temp immediately gives an initial value after definition, no problem will occur.