【C++】如何使用数组区间作为参数传入函数中?如何使用const指针传递数组?

指针传递数组方法:

  1. 将指向数组起始位置的指针做为一个参数,将数组长度作为第二个参数。(指针之处数组的位置和数据类型)
  2. 即指定元素区间,可以传递两个指针来完成,一个指针标识 数组的开头,另一个 指针标识数组的尾部

本文重点关注第2种方法: 

// 使用数组区间的函数
//注意,8个元素的话,数组是a[0]~a[7]。而为什么+8?这是为了让它指向最后元素的下一个位置
#include <iostream>
const int ArSize = 8;
int sum_arr(const int * begin, const int * end);
int main()
{
	using namespace std;
	int cookies[ArSize] = { 1, 2, 3, 4, 5, 6, 7, 8 };

	int sum = sum_arr(cookies, cookies + ArSize);
	cout << "总数:  " << sum << endl;
	sum = sum_arr(cookies, cookies + 3);//前3个元素
	cout << "前三个总数:  " << sum << endl;
	sum = sum_arr(cookies + 4, cookies + 8);//最后4个元素
	cout << "最后四个总数:  " << sum << endl;
	cin.get();
	return 0;
}

//传递数组区间
int sum_arr(const int * begin, const int * end)
{
	const int * pt;
	int total = 0;

	for (pt = begin; pt != end; pt++)
		total = total + *pt;
	return total;
}

注意:当pt等于end时,它将指向区间最后一个元素后面的一个位置,循环结束。

运行结果:

                          

const 限定了指针传递地址,地址是常量,而指向的数据可以更改。(地址不可以改变,在这个地址上的数据可以改变)

猜你喜欢

转载自blog.csdn.net/qq_15698613/article/details/85244077