c语言库函数传参数,以及地址和指针的理解

之前发布了一条博客,里面的代码存在部分问题,以及问题的解答

​

#include "stdio.h"
void Swap(int x,int y)
{
	int temp=0;
	temp=x;
	x=y;
	y=temp;
}
 max(int x,int y)
{
	int q=0;
	if(x>y)
		q=x;
	else 
		q=y;
	return q;
}
int main()
{
	int a=10;
	int b=20;
	Swap(a,b);
max(a,b);
printf("%d \n",a);
printf("%d\n",max(a,b));}

[点击并拖拽以移动]
​
10
20
Press any key to continue

在这段代码中并没有成功实现a,b的正确传递,原因是x,y也分别有自己的空间,传值过去后并不能正确的输出。

解决办法如下:

#include "stdio.h"
void Swap(int* x,int* y)
{
	int temp=0;
	temp=*x;
	*x=*y;
	*y=temp;
}
 max(int x,int y)
{
	int q=0;
	if(x>y)
		q=x;
	else 
		q=y;
	return q;
}
int main()
{
	int a=10;
	int b=20;
	
	Swap(&a,&b);
max(a,b);
printf("%d %d\n",a,b);
printf("%d\n",max(a,b));}

竟然有多余的空间导致交换无法进行,那么我们就使用指针来交换,传指针即可解决上面问题

20 10
20
Press any key to continue

这样才是正确的传递做法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值