I just did a basic study of pointers, so what is the role of pointers? Let's use the Swap function for analysis.
Suppose we want to swap the values of a and b
void Swap(int a, int b)//交换不成功
{
int tmp = a;
a = b;
b = tmp;
}
int main()
{
int a = 10;
int b = 20;
printf("交换前:%d,%d\n",a,b)
Swap(a,b)
printf("交换后:%d,%d\n",a,b)
return 0;
}
Let's look at the picture
and see that the addresses are different. The value exchange of a and b in the Swap function will not affect the variables in main, and here it is only passed by value (copy).
If you want to modify the value in main in the Swap function, you must break through the restrictions between different functions, then we must introduce pointers, let's look at the second one.
void Swap(int *p1,int *p2)//交换不成功
{
int *tmp = p1;
p1 = p2;
p2 = tmp;
}
int main()
{
int a = 10;
int b = 20;
Swap(&a,&b);
printf("%d %d\n",a,b)
return 0;
}
We found that it is still unsuccessful, let's take a look at the picture.
It can be seen from the figure that the contents of p1 and p2 are indeed exchanged, but the values of a and b are not exchanged. To exchange, we must dereference.
Check out the third edition
void Swap(int *p1,int *p2)//程序崩溃
{
int *tmp;
*tmp=*p1;
*p1=*p2
*p2=*tmp;
}
int main()
{
int a = 10;
int b = 20;
Swap(&a,&b);
printf("%d %d\n",a,b);
return 0;
}
When the above code is run, the program crashes. The compiler will warn you about the use of uninitialized local variables at compile time. This is because we use wild pointers.
Wild pointer: Also called a dangling pointer, it is an address that we do not have access to. This address may not exist, or it may exist but we cannot access it. Then we eliminate the wild pointer and look at the fourth type:
void Swap(int *p1,int *p2)
{
int tmp;
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
int main()
{
int a = 10;
int b = 20;
printf("交换前:%d,%d\n"a,b);
Swap(&a,&b);
printf("交换后:%d,%d\n"a,b);
return 0;
}
Look at the execution results:
Let's look at the process
Conclusion: If the change of the called function wants to affect the calling function, it must 1. Pass the pointer 2. Dereference (access).
Finally finished. . .