问题描述
尝试传递以1开头的连续数字的int数组,但假设接收此数组的函数不知道其长度。尝试计算函数内部的长度时,它只会给我1,因为它仅在计算sizeof(arrayName)时会找到第一个元素。
Trying to pass an int array of consecutive numbers starting with 1 but assuming the function receiving this array does not know it's length. When trying to calculate the length inside the function it just gives me 1 since it only finds the first element when calculating sizeof(arrayName).
#include <iostream>
using namespace std;
int Sum(int intArray[]) {
int n = sizeof(intArray) / sizeof(*intArray);
cout << "Array size in function: " << n << endl;
return n * (n + 1) / 2;
}
int main() {
int anArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int arraySum = Sum(anArray);
cout << "Array size in main: " << sizeof(anArray) / sizeof(*anArray) << endl;
cout << "Sum is: " << arraySum;
int a;
cin >> a;
return 0;
}
推荐答案
您的函数正在使用指针诠释。当您将数组传递到指针时,所有大小信息都会丢失。但是您可以使用函数模板来实例化与正确的数组大小匹配的函数:
Your function is taking a pointer to int. All size information is lost as you pass the array into the pointer. But you can use a function template to instantiate functions that match the right array size:
template <size_t N>
int Sum(const int (&intArray)[N])
{
cout << "Array size in function: " << N << endl;
return std::accumulate(std::begin(intArray), std::end(intArray), 0);
}
此 Sum
函数将接受编译时已知的纯数组或大小。但是,在这些情况下使用 std :: array
更为合理,在以下情况下使用 std :: vector
This Sum
function will accept plain arrays or size known at compile time. However, it makes more sense to use std::array
for these cases, or std::vector
for cases when the size is chosen at runtime.
请注意,调用 std :: accumulate
只是解决该问题的一个示例总和问题。它不需要 N
的知识,并且可以完全替换该功能。大小由 std :: begin
和 std :: end
照顾。您需要标题< numeric>
和< iterator>
标头,用于累积
和开始/结束
。
Note that the call to std::accumulate
is just an example that solves the sum problem. It does not require knowledge of N
, and could replace the function entirely. The size is taken care of by std::begin
and std::end
. You would need headers <numeric>
and <iterator>
for accumulate
and begin/end
respectively.
这篇关于C ++-传递未知大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!