指针作为形参改变实参的引用(C++初学笔记)

指针部分一直是难理解的,特意做笔记如下,直接上代码

#include<iostream>
using namespace std;

void swap1(int a,int b);
void swap2(int* p1, int* p2);
void swap3(int* p1, int* p2);

int main() {

	int a = 1, b = 2;
	cout << "---------------swap1---------------------" << endl;
	swap1(a, b);//swap1内的交换不改变外部a和b的值
	cout << "swap1 a=" << a << endl;
	cout << "swap1 b=" << b << endl;
	cout << "---------------swap2---------------------" << endl;
	swap2(&a, &b);//swap2内的交换不改变外部a和b的值
	cout << "swap2 a=" << a << endl;
	cout << "swap2 b=" << b << endl;
	cout << "---------------swap3---------------------" << endl;
	swap3(&a, &b);
	cout << "swap3 a=" << a << endl;
	cout << "swap3 b=" << b << endl;

}

void swap1(int a,int b){//值传递,形参不改变实参
	int temp = a;
	a = b;
	b = temp;
	cout << "in swap1 a=" << a << endl;
	cout << "in swap1 b=" << b << endl;

}

void swap2(int* p1, int* p2) {//指针传递,虽然传递的是指针,但是在交换的是形参指针,实际指向a和b的指针不变
	int* p3 = p1;
	p1 = p2;
	p2 = p3;
	cout << "in swap2 a=" << *p1 << endl;
	cout << "in swap2 b=" << *p2 << endl;
}
void swap3(int* p1, int* p2) {//指针传递,对传过来的实参的指针进行交换,所以最终在内存中,a和b的指针指向发生了变化
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
	cout << "in swap3 p1=" << *p1 << endl;
	cout << "in swap3 p2=" << *p2 << endl;
}

输出结果:

---------------swap1---------------------
in swap1 a=2
in swap1 b=1
swap1 a=1
swap1 b=2
---------------swap2---------------------
in swap2 a=2
in swap2 b=1
swap2 a=1
swap2 b=2
---------------swap3---------------------
in swap3 p1=2
in swap3 p2=1
swap3 a=2
swap3 b=1

自己创建的两个群,一个是做3D方面的(包括算法图像处理,以及三维模型生成等),另一个是代码编程群,两个群都是为了交流技术的,欢迎加入,禁止发广告。

在这里插入图片描述在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路卿老师

大哥大姐给点吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值