函数和数组
前言
函数可用来处理复杂的类型,那么本节将详细介绍数组和函数结合在一起。
下面举一个例子:
假设用一个数组来记录家庭野餐中每个人吃了多少甜品(每个数组索引对应一个人,元素值对应与这个人所持的甜品数量)。现在想知道总数。
#include<iostream>
using namespace std;
const int ArSize = 8;
int sum_arr(int arr[], int n);
int main()
{
int cookies[ArSize] = { 1,2,4,8,16,32,64,128 };
int sum=sum_arr(cookies, ArSize);
cout << "Total cookies eaten:" << sum << endl;
return 0;
}
int sum_arr(int arr[], int n)
{
int total = 0;
for (int i = 0; i < n; i++)
total += arr[i];
return total;
}
函数如何使用指针来处理数组
C++与C语言一样,也将数组名是为指针,将数组名解释为其第一个元素的地址。
cookies=&cookies[0];//arry name is address of first element
例外:
- 数组声明使用数组名来标记存储位置。
- 对数组名使用sizeof 将得到整个数组的长度。
- 将地址运算符&用于数组名时,将返回整个数组的地址。
上述代码中,int arr[]和int *arr的含义相同,且仅在用于函数头或函数原型中才成立。它们意味着arr是一个int指针,然而,数组表示法提醒用户是一个数组。
另外:
arr[i]==*(ar+i);//values in two notations
&arr[[i]==ar+i;//addresses in two natations
将指针(数组名)加1,实际上是加上了一个与指针指向的类型长度相等的值,对于遍历数组而言,使用指针加法和数组下标时等效。
将数组作为参数意味着什么
上述程序中,函数调用sum_arr(cookies,ArSize)将cookies的地址赋给指针变量arr,将ArSize赋给int变量n。这意味着,程序实际上并未将数组内容传递给函数,而是将数组的位置,包含元素的种类以及元素数目提交给函数。
将数组地址作为参数可以节省复制整个数组所需的时间和内存,如果数组很大,则使用拷贝的系统的开销非常大,程序不仅需要更多的计算机内存,还需要花费时间来复制大快数据。另一方面,使用原始数据增加了破坏数据的风险性。
下面代码将显示arr[]与arr的区别:
#include<iostream>
using namespace std;
const int ArSize = 8;
int sum_arr(int arr[], int n);
int main()
{
int cookies[ArSize] = { 1,2,4,8,16,32,64,128 };
int sum = sum_arr(cookies, ArSize);
cout << "Total cookies eaten:" << sum << endl;
return 0;
}
int sum_arr(int arr[], int n)
{
int total = 0;
for (int i = 0; i < n; i)
total = total + arr[i];
return total;
}
由上述代码可知,cookies与arr指向同一个地址,但sizeof cookies的值为32,但sizeof arr为8,这是因为sizeof cookies是整个数组的长度,而sizeof arr只是指针变量的长度。