#include<stdio.h>
void swap(int* str1,int* str2)
{
int p=0;
p = *str1;
//*str1结果是p1的地址,p1的地址又指向a,所以P的值是5
*str1 = *str2;
//相等与a=b
*str2 = p;
//*str2是b的地址,而p的值是5,把5赋值给b
}
int main()
{
int a = 5,b = 7;
int* p1,*p2;
p1 = &a;
p2 = &b;
swap(p1,p2);
//实参是在传地址
printf("%d,%d\n",a,b);//7,5
printf("%d,%d",*p1,*p2);//7,5
}
搞清楚p = str1和p = *str1 的区别
#include<stdio.h>
void swap(int* str1,int* str2)
{
int p;
p = str1;
str1 = str2;
str2 = p;
}
int main()
{
int a = 5,b = 7;
int* p1,*p2;
p1 = &a;
p2 = &b;
swap(p1,p2);
printf("%d,%d\n",a,b);
printf("%d,%d",*p1,*p2);
}
//这种直接报错
//p是变量,而str是指针地址
//第一个案例中,p=*str
#include<stdio.h>
void swap(int* str1,int* str2)
{
int* p;
//这里定义了一个指针变量
p = str1;
//指针变量p指向了str1
str1 = str2;
//原本str1是指向p1的现在str1指向了str2
str2 = p;
//而str2原本指向p2现在str2指向了p
}
int main()
{
int a = 5,b = 7;
int* p1,*p2;
p1 = &a;
p2 = &b;
swap(p1,p2);
printf("%d,%d\n",a,b);//函数swap的操作不影响a,b
printf("%d,%d",*p1,*p2);//函数swap的操作不影响p1和p2的指向
//相当于把p1和p2的地址先给str1和str2指向,结果str1和str2有指向了新的内存单元,所以不影响
}