Trying to practice recursive function.
Not sure why the expression sizeof(p) / sizeof(p[0]) cannot be used here.
When compiling, it gives out "CH15.5.cpp: In function 'void sumArray(int*, int&, int&)':
CH15.5.cpp:21:27: warning: 'sizeof' on array function parameter 'p' will return size of 'int*' [-Wsizeof-array-argument]
21 | if(counter < (sizeof(p) / sizeof(p[0])))
| ^
CH15.5.cpp:19:19: note: declared here
19 | void sumArray(int p[],int & counter,int& sum)
| ~~~~^~~
"
the best solution is to use something that knows how big it is, like a <vector>.
arrays have a place of course, but std::array also knows its own size, so the raw C style arrays are less useful for most tasks. I still use them, but not if I have to pass the size around or compute it ... more for small lookup tables that have a fixed size.
#include <iostream>
int sumArray( int *p, int n );
int main()
{
int p[] = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 };
std::cout << sumArray( p, sizeof p / sizeof p[0] );
}
int sumArray( int *p, int n )
{
if ( !n ) return 0;
return *p + sumArray( p + 1, n - 1);
}