Why use pointer 2: The
pointer variable is used as a function parameter, and the address of a variable can be transferred to another function;
for example, the following function can be implemented: the input two integers are output according to the size (processed by the function method)
#include <stdio.h>
int main()
{
void swap(int *p1, int *p2);
int a, b;
int *n1, *n2;
scanf_s("%d,%d", &a, &b);
n1 = &a;
n2 = &b;
if (a < b) swap(&a, &b);
printf("max =%d,min =%d\n,", a, b);
return 0;
}
void swap(int *p1,int *p2)
{
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
The result is to swap the value of ab, but the values of p1 and p2 remain unchanged;
But if you change the swap function to
#include <stdio.h>
int main()
{
void swap(int p1, int p2);
int a, b;
int *n1, *n2;
scanf_s("%d,%d", &a, &b);
n1 = &a;
n2 = &b;
if (a < b) swap(a, b);
printf("max =%d,min =%d\n,", a, b);
return 0;
}
void swap(int p1,int p2)
{
int temp;
temp = p1;
p1 = p2;
p2 = temp;
}
The result is incorrect. The reason is: after the swap function is executed, the values of x and y are exchanged, but the values of a and b are not affected. At the end of the function, the variables x and y are released, and a, b in the main function , There is no exchange, and the change of the formal parameter value cannot cause the actual parameter value to change with it.
That is to say, in order to change the value of some variables in the main function, the pointer variable should be used as the function parameter. When the function is executed, the value pointed to by the pointer variable will change, which is why the pointer is used;