C++ - passing an array of unknown size
arrays, c++, pointers
Solution
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);
}
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.
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.
Problem
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; } ```