Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Max and min element of an array using functions and pointers

I have a task to make two functions: max_el function that needs to return the pointer to the largest element in the array; and min_el function that needs to return the pointer to the smallest element in the array. I have this so far, and for some examples it works, for some it crashes and for some the output isn’t right. I really don’t know where I messed up.

int *max_el(int *p1, int *p2){
int max,i;
for(i=p1; i<p2; i++){
    if(*p1>*p2){
        max=*p1;
    }
    p2++;
}
return p1;
}
int *min_el(int *p1, int *p2){
int min,i;
for(i=p1; i<p2; i++){
    if(*p1<*p2){
        min=*p1;
    }
    p2++;
}
return p1;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your code is wrong for several reasons. Missing initialization, wrong assignments, wrong compares, etc. For instance you would want i and max to be pointers instead of integers.

Take a look at this:

int *max_el(int *p1, int *p2)
{
    int *max = p1; // Set the max pointer to point to first element
    int *i;

    for(i = p1 + 1; i < p2; i++)
    {
        if(*i > *max)   // Compare current element with max element
        {
            max= i;
        }
    }
    return max;    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading