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

指针(三):指针与函数

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

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.排列数公式:表示的含义是从n个数中选出m个进行排队,有多少种不同的排法。从n个不同的元素中任取m(m≤n)个元素的所有排列的个数,叫做从...

编程与编程语言

编程与编程语言

一、编程是什么编程就像给电脑写“魔法指令”!电脑很聪明,但它不会自己思考,需要你告诉它做什么和怎么做。比如,你想让电脑画一只小猫、做一个游戏,或者解一道数学题,都需要用编程语言写下规则。举个栗子🌰:如...

最小生成树—Prim(普里姆)算法

最小生成树—Prim(普里姆)算法

一、算法概述Prim 算法是一种用于求解加权无向连通图的最小生成树(MST) 的贪心算法。它从一个顶点开始,逐步扩展生成树,每次选择连接已选顶点集和未选顶点集的最小权重边。二、算法思想初始化:从任意顶...

【贪心】区间选点

【贪心】区间选点

【题目描述】数轴上有n个闭区间[ai, bi],取尽量少的点,使得每个区间内都至少有一个点。(不同区间内含的点可以是同一个,1<=n<=10000,1<=ai<=bi<=...

组合数的写法

前面我们写过 全排列和排列数 等。这篇文章。我们写一下组合数。例题:从n个数中,选出m个,一共有多少种不同的选法?这是一道典型的组合数公式。我们直接用dfs公式肯定会出现重复的。#include<...

判断闰年

代码参考:#include<iostream>  using namespace std; //判断闰年的函数  int leap(...