当前位置:首页 > C++目录 > 正文内容

指针(三):指针与函数

亿万年的星光5年前 (2021-08-10)C++目录1734

1.交换的例子

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void swap(int x, int y){
	int a=x;
	x=y;
	y=a;
	cout<<"函数内部"<<x<<" "<<y<<endl; // 4 3
}
int main() {
	int a=3,b=4;
	swap(a,b);
	cout<<a<<" "<<b<<endl;  // 3 4
	return 0;
}

上面的程序不能完成交换

而下面的程序可以完成交换

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void swap(int &x, int &y){
	int a=x;
	x=y;
	y=a;
	cout<<"函数内部"<<x<<" "<<y<<endl; // 4 3
}
int main() {
	int a=3,b=4;
	swap(a,b);
	cout<<a<<" "<<b<<endl;  // 4 3
	return 0;
}

2.指针作为函数参数

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void swap(int *x, int *y){
	int t =*x;
	*x= *y;
	*y=t;
	cout<<*x<<" "<<*y<<endl; // 4 3
}
int main() {
	int a=3,b=4;
	swap(&a,&b);
	cout<<a<<" "<<b<<endl;  // 4 3
	return 0;
}

上面的这样的例子可以完成交换。

下面的例子可以直接修改原来数据的值

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void swap(int *x, int *y){
	*x=5; 
}
int main() {
	int a=3,b=4;
	swap(&a,&b);
	cout<<a<<" "<<b<<endl;  //5 4
	return 0;
}



    扫描二维码推送至手机访问。

    版权声明:本文由青少年编程知识记录发布,如需转载请注明出处。

    分享给朋友:

    相关文章

    【数据结构】优先队列(1)

    优先队列(Priority Queue)是一种特殊的队列,它 不遵循“先进先出”(FIFO) 的原则,而是 按照优先级(Priority) 来出队。优先级高的元素 先出队,优先级低的元素 后出队。1....

    常见的数据范围

    一、总结名称字节位数(二进制)最小值最大值位数(十进制)bool18011char18shrot 216    (-2^15  到2^15  -1)-...

    【初级篇】求最大公约数的方法

    1.辗转相除法int gcd(int a,int b)  {       if(a%b==0...

    如何使用code::blocks编写C++代码

    如何使用code::blocks编写C++代码

    在前面的文章中,已经简单介绍了如何下载code::blocks了,这篇文章介绍一下如何使用code::blocks编写一个C++代码我们打开code::blocks软件,点击”New File“然后点...

    【题解】最短路径问题

    【题目描述】平面上有n个点(n≤100),每个点的坐标均在-10000~10000之间。其中的一些点之间有连线。若有连线,则表示可从一个点到达另一个点,即两点间有通路,通路的距离为两点间的直线距离。现...

    数组的不确定长度输入

    0.前言我们在学习数组的时候一般都会告诉你数组的长度,然后for循环去遍历。但是有一类问题是没有n的,也就是没有告诉长度的。1.方法第一种:(数组)#include<iostream>...