当前位置:首页 > C++知识 > 正文内容

指针(三):指针与函数

亿万年的星光3年前 (2021-08-10)C++知识699

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;
}



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

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

分享给朋友:

相关文章

信息学奥赛中文件流的写法

信息学奥赛中文件流的写法

头文件#include<cstdio>也可以用万能头格式如下:int main(){ freopen("xxxx.in","r",st...

【数据结构】栈—括号匹配检验

【数据结构】栈—括号匹配检验

【题目描述】假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,如([ ]())或[  (  [  ] [  ] ) ] 等为正确的匹配,[&nbs...

【题解】组合数学

【题解】组合数学

一、排列与组合口诀:有序排列,无序组合,分类相加,分步相乘。1.排列数公式:表示的含义是从n个数中选出m个进行排队,有多少种不同的排法。从n个不同的元素中任取m(m≤n)个元素的所有排列的个数,叫做从...

unsigned

在一些代码中,经常能看到unsigned这种数据类型,比如下面这样的。#include<iostream> using namespace std; int&nbs...

拓扑排序

拓扑排序

一、定义对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边<u,v>∈E(G),则...

如何判断回文数/回文串

所谓回文,就是从左往右读和从右往左读都是一样的,这样的数字或者字符称为回文数/回文字符。做题的时候经常能看到判断回文操作。判断回文的一般有两种,一种是数字类型,一种是字符类型。两种分别介绍一下。一、回...