在本文中,您将学习将数组传递给C ++中的函数。您将学习如何传递一维和多维数组。
数组可以作为参数传递给函数。也可以从函数返回数组。考虑以下示例,将一维数组传递给函数:
C ++程序通过将一维数组传递给函数来显示5个学生的分数。
#include <iostream>
using namespace std;
void display(int marks[5]);
int main()
{
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
void display(int m[5])
{
cout << "显示分数: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "Student "<< i + 1 <<": "<< m[i] << endl;
}
}
输出结果
显示分数:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69
将数组作为参数传递给函数时,仅将数组名称用作参数。
display(marks);
还要注意将数组作为参数与变量传递时的区别。
void display(int m[5]);
上面代码中的参数marks表示数组marks[5]的第一个元素的内存地址。
函数声明中的形式参数int m [5]转换为int * m;。 该指针指向由数组marks指向的相同地址。
这就是原因,尽管该函数是在用户定义的函数中使用不同的数组名称m[5]进行操作,但是原始数组仍在marks进行操作。
C ++以这种方式处理将数组传递给函数以节省内存和时间。
多维数组可以通过与一维数组相似的方式传递。考虑以下示例,将二维数组传递给函数:
C ++程序通过将二维数组的元素传递给函数来显示它。
#include <iostream>
using namespace std;
void display(int n[3][2]);
int main()
{
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
};
display(num);
return 0;
}
void display(int n[3][2])
{
cout << "显示值: " << endl;
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 2; ++j)
{
cout << n[i][j] << " ";
}
}
}
输出结果
显示值:
3 4 9 5 7 1
在上面的程序中,多维数组num被传递给函数display()。
在display()函数内部,使用嵌套的for循环遍历数组n(num)。
该程序使用2个for循环遍历二维数组中的元素。如果是一个三维数组,那么应该使用3 for循环。
最后,所有元素都被打印到屏幕上。
注意: 维度大于2的多维数组可以以类似于二维数组的方式传递。
C++ 不允许返回一个完整的数组作为函数的参数。但是,您可以通过指定不带索引的数组名来返回一个指向数组的指针。
如果您想要从函数返回一个一维数组,您必须声明一个返回指针的函数,如下:
int * myFunction()
{
.
.
.
}
另外,C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为 static 变量。
现在,让我们来看下面的函数,它会生成 10 个随机数,并使用数组来返回它们,具体如下:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// 要生成和返回随机数的函数
int * getRandom( )
{
static int r[8];
// 设置种子
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 8; ++i)
{
r[i] = rand();
cout << r[i] << endl;
}
return r;
}
// 要调用上面定义函数的主函数
int main ()
{
// 一个指向整数的指针
int *p;
p = getRandom();
for ( int i = 0; i < 8; i++ )
{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
30737
23110
21765
14820
8295
12330
28395
191
*(p + 0) : 30737
*(p + 1) : 23110
*(p + 2) : 21765
*(p + 3) : 14820
*(p + 4) : 8295
*(p + 5) : 12330
*(p + 6) : 28395
*(p + 7) : 191