-1

I trying to pass an array but don't understand why it gives me those errors. The code is also available in ideone.com

#include <iostream>

using namespace std;

class Max
{
   int max = 0;

   public:
      int getMax(int array[], int size)
      {
          for(int num : array)
          {
                if(num > max)
                    max = num;
          }
          return max;
      }
};

int main( )
{
   Max m;
   int arr[5] = { 5, 3, 2, 7, 6 };
   cout << "Max number is: " << m.getMax(arr,5);

   return 0;
}
a1204773
  • 6,923
  • 20
  • 64
  • 94

3 Answers3

1

The problem here as has been mentioned is that passing an array to a function it decays to a pointer. The fix that involves the least changes is to pass the array by reference like so:

template <int U>
int getMax(int (&array)[U])

this fix is probably not the most intuitive for a beginner though. The fix that requires a bit more changes and probably makes more sense to a beginner is to use std::vector or std::array:

int getMax(const std::vector<int> &array)

and in main:

std::vector<int> arr = { 5, 3, 2, 7, 6 };
cout << "Max number is: " << m.getMax(arr);
Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0
  1. size argument needs type specified (proper type is size_t).
  2. array in getMax function is a pointer (not an array). You can't use range-based for loop with it. You have to use regular for loop which will make use of size argument.
n0rd
  • 11,850
  • 5
  • 35
  • 56
0

The cause is the for(:) can not get the size of "int array[]".

You have a size argument, but the begin() & end() can not use it. You must wrap the begin() and end() member functions or just simple it to

for(int i = 0; i< size; i++)
{
   int num = array[i];
   if(num > max)
      max = num;
}
Kaiji
  • 1