传递数组作为函数参数在C ++中 [英] Passing array as function parameter in C++
问题描述
据我所知,一个数组可以传递给函数在不少方面。
I am aware that an array can be passed to a function in quite a few ways.
#include <iostream>
#include <utility>
using namespace std;
pair<int, int> problem1(int a[]);
int main()
{
int a[] = { 10, 7, 3, 5, 8, 2, 9 };
pair<int, int> p = problem1(a);
cout << "Max =" << p.first << endl;
cout << "Min =" << p.second << endl;
getchar();
return 0;
}
pair<int,int> problem1(int a[])
{
int max = a[0], min = a[0], n = sizeof(a) / sizeof(int);
for (int i = 1; i < n; i++)
{
if (a[i]>max)
{
max = a[i];
}
if (a[i] < min)
{
min = a[i];
}
}
return make_pair(max,min);
}
以上我code仅通过而应当传递数组(或在技术上,一个指针数组)的第一个元素,因此,其输出为10,10为最大值和最小值(即[0 ]只)。
My code above passes only the first element while it should be passing an array (or technically, a pointer to the array) and hence, the output is 10, 10 for both max and min (i.e. a[0] only).
我是什么做错了,我想这是正确的方式。
What am I doing wrong, I guess this is the correct way.
推荐答案
的数组的内容被传递给函数。问题是:
The contents of the array are being passed to the function. The problem is:
n = sizeof(a) / sizeof(int)
不给你数组的大小。一旦你通过数组给一个函数你不能再得到它的大小。
Does not give you the size of the array. Once you pass an array to a function you can't get its size again.
由于您没有使用动态数组可以使用 的std ::阵列
这不记得它的大小。
Since you aren't using a dynamic array you can use a std::array
which does remember its size.
您也可以使用:
template <int N>
void problem1(int (&a) [N])
{
int size = N;
//...
}
这篇关于传递数组作为函数参数在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!