I'm trying to get the length of an array passed as a parameter on some function. The code is look like this :
double getAverage(int numbers[])
{
int length = sizeof(numbers)/sizeof(numbers[0]);
// here the result of the length is 1.
int sum = 0;
for (int i = 0 ; i < length ; i++)
{
sum += numbers[i];
}
return (double)sum / length;
}
int main()
{
int numbers[8] = {1,2,3,4,5,6,7,8};
//if I call here sizeof(numbers)/sizeof(numbers[0] the result will be 8 as it
//should be.
cout << getAverage(numbers) << endl;
return 0;
}
My question is how to get the array length which is passed as argument of a function by reference(although I know that every array is passed by reference)? I know that there is a lot of questions about finding the array length in C/C++ but no one of them give me the answer which I'm looking for. Thanks in advance.
std::vector<T>orstd::array<T, N>.sizeof(x)/sizeof(x[0])approach... There are type safe alternatives in C++ (beyond using vector) to obtain the size of an array that would have detected your error at compile time.