Blog Archive

Wednesday, June 20, 2018

C++ Passing Arrays & Vectors to Functions

Source:
https://www.tutorialspoint.com/cplusplus/cpp_passing_arrays_to_functions.htm

Note:
Way 1:
double getAverage(int arr[], int size) {
  int i, sum = 0;       
  double avg;          

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

   return avg;
}

Way 2:
double getAverage(int *arr, int size) {
  int i, sum = 0;       
  double avg;          

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

   return avg;
}

About calling the function:
vector<int> ivec({1,2,3});
getAverage(&iVec[0], iVec.size()); // Way 2 calling



Summary:
Note, the following two function signatures are the same
double getAverage(int arr[], int size)
double getAverage(int *arr, int size) 

No comments:

Post a Comment