-3

enter image description here

I made that task but it turn to me a huge number not the maximum

my code is

    #include <iostream>
    using namespace std;
    int* max(int p[],int n);
   int main (){
     int n;
     int*A=new int;


int *p;

cout<<"enter the value of array";
cin>>n;
p=new int[n];
for(int i=0;i<n;i++){
cout<<"enter the element";
cin>>p[n];
}
A=(max(p,n));
cout<<"the maximum is"<<*A;
return 0;

}
int* max(int p[],int n)
{
   int maximum;
   maximum = p[0];
   for(int x=0;x<n;x++)
   {
       if(p[x]>maximum)
       {
           maximum=p[x];
           return &maximum;
       }
   }

   return  &maximum;
}
Salma
  • 1
  • 1
  • 3

1 Answers1

0

The correct definition of the function can look the following way

int * max( int a[], size_t n )
{
    int *maximum = a;

    for ( size_t i = 1; i < n; i++ )
    {
        if ( *maximum < a[i] ) maximum = a + i;
    }

    return maximum;
}

Or

int * max( int a[], size_t n )
{
    int *maximum = a;

    if ( n != 0 )
    {
        for ( int *p = a + 1; p != a + n; ++p )
        {
            if ( *maximum < *p ) maximum = p;
        }
    }

    return maximum;
}

As for your function definition then you are returning pointer to a local variable that in general case will be destroyed after exiting the function. So the program has undefined behaviour.

Take into account that there is no any sense to allocate memory

int*A=new int;

You will get a memory leak.

Simply define

int *A;

Also you should know that there is standard algorithm std::max_element declared in header <algorithm> that performs the same task.

For example you could write

#include <algorithm>

//..

A = std::max_element( p, p + n );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335