Please check the following code and explain what is meant by passing the address of the array. Shall we send the name of the array preceeded by & or * or just the array name or what. Also, how do we pass the arguments to the function amax(). Shall we preceed the array name with * or & or we send just the name of the array?
/*Create a function called amax() that returns the value of the largest element in an array.
The arguments to the function should be the address of the array and its size.
Make this function into a template so it will work with an array of any numerical type.
Write a main() program that applies this function to arrays of various types
*/
#include <iostream>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
//Definition of the function template amax() starts below:
template <typename T>
T amax( const T& array, const int maxSizeOfArray )
{
T maxValue = array[0];
for(int i = 0; i < maxSizeOfArray; i++)
if (array[i] > maxValue)
maxValue = array[i];
return maxValue;
}
//main function begins here.
int main()
{
int a[4] = {92, 764, 906, 658};
double b[3] = {322.72, 874.40, 766.86};
long c[5] = {-2, 4, 6, 8, 10};
passing const T& array argument to amax function means that it takes one element of type T as a reference, not an array, if you want to pass an array, you should mention that it is array:
template <typename T>
T amax(const T[] array, const int& maxSizeOfArray)
{
T maxValue = array[0];
for(int i = 0; i < maxSizeOfArray; i++)
if (array[i] > maxValue)
maxValue = array[i];
return maxValue;
}
or which is the same you can pass a pointer T *. When calling the function, you can use the name of array or the address of it, or the address of the first element, which are the same.
int arr[10];
..... //initialize the array;
cout<<amax(arr, 10);
cout<<amax(&arr, 10);
cout<<amax(&arr[0], 10);