0

This is a question on C++. I tried defining a function that computes the average of all elements in an array of doubles as follows, through the sizeof function that enables us to compute the length of the array.

#include<iostream>
#include<cstddef>

using namespace std;

double getAverage(double arr[]) {
  double sum =0;       
  double avg;          
  size_t size = sizeof(arr)/sizeof(*arr);  \\ to calculate the length of the array arr

   for (size_t i = 0; i < size; ++i) {
      sum += arr[i];
   }
   avg = sum / size;

   return avg;
}

int main () {
   double balance[] = {1000, 2, 3, 17, 50};
   double avg = getAverage(balance) ;
   cout << "Average value is: " << avg << endl; 
   return 0;
}

However, instead of 214.4, it returns 1000, which is clearly wrong. Is it legitimate to pass an array as an argument of a function in C++?

Richard
  • 131
  • 3

0 Answers0