八、C++指针(2)

29 篇文章 0 订阅
本文介绍了C++中指针的基本用法,包括如何利用指针访问数组元素,以及指针作为函数参数时的不同效果,如值传递与地址传递。此外,还展示了如何封装冒泡排序函数对整型数组进行升序排序的示例。
摘要由CSDN通过智能技术生成

一、指针和数组

作用:利用指针访问数组中元素

#include<iostream>
using namespace std;

int main()
{
	//指针和数组
	//利用指针访问数组中的元素

	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };

	cout << "第一个元素为:" << arr[0] << endl;

	int* p = arr;	//arr就是数组的首地址
	cout << "利用指针访问第一个元素:" << *p << endl;
	p++;	//让指针向后偏移4个字节
	cout<<"利用指针访问第二个元素:" << *p << endl;

	cout << "利用指针遍历数组" << endl;
	int* p2 = arr;
	for (int i = 0; i < 10; i++)
	{
		//cout << arr[i] << endl;
		cout << *p2 << endl;
		p2++;    //指针偏移
	}
	system("pause");
	return 0;
}

运行结果:

第一个元素为:1
利用指针访问第一个元素:1
利用指针访问第二个元素:2
利用指针遍历数组
1
2
3
4
5
6
7
8
9
10

二、指针和函数

作用:利用指针作函数参数,可以修改实参的值

#include<iostream>
using namespace std;
//实现两个数字进行交换
void swap01(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;
	cout << "swap01中 a = " << a << endl;
	cout << "swap01中 b = " << b << endl;
	cout << endl;
}

void swap02(int* p1, int* p2)
{
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
	cout << "swap02中 *p1 = " << *p1 << endl;
	cout << "swap02中 *p2 = " << *p2 << endl;
}

int main()
{
	//指针和函数
	//1、值传递可以实参的值,不可以修改实参ab的值
	int a = 10;
	int b = 20;
	swap01(a, b);

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << endl;

	//2、地址传递
	//如果是地址传递,可以实参ab的值
	swap02(&a, &b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	system("pause");
	return 0;
}

运行结果:

swap01中 a = 20
swap01中 b = 10

a = 10
b = 20

swap02中 *p1 = 20
swap02中 *p2 = 10
a = 20
b = 10

三、指针、数组、函数

描述:封装一个函数,利用冒泡排序,实现对整型数组的升序排序

例如数组:

int arr[10]={4,5,3,2,6,7,10,9,1,8}
#include<iostream>
using namespace std;
//冒泡排序函数	参数1	数组的首地址	参数2	数组长度
void bubbleSort(int* arr, int len)	//使用指针传递
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
			//如果j>j+1的值,交换数字
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}

//打印数组
void prnitArry(int* arr, int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << endl;
	}
}

int main()
{
	//1、创建数组
	int arr[10] = { 4,5,3,2,6,7,10,9,1,8 };

	//数组长度
	int len = sizeof(arr) / sizeof(arr[0]);		//数组长度/单个数组元素长度
	//2、创建函数,实现冒泡排序
	bubbleSort(arr, len);

	//3、打印排序后的数组
	prnitArry(arr, len);

	system("pause");
	return 0;
}

运行结果:

1
2
3
4
5
6
7
8
9
10

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

黄金圣手

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值