指针常见传址,传值

#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有指向了新的内存单元,所以不影响
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值