0

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;
}
1
  • i is an integer. p1 is a pointer to an integer. So doing i=p1 is wrong. Makes no sense. You probably want i to be a pointer to int Commented Jan 29, 2022 at 16:28

3 Answers 3

1

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;    
}
Sign up to request clarification or add additional context in comments.

Comments

0

Let's look at your max_el() function first.

To begin with, you don't initialize max. What if your compiler sets it to 0 by default, and all your array elements are negative?

Also, you're assigning a pointer to an int -- take a closer look at that. Finally, look at your type for i -- is that really what you want?

Comments

0

First of all, you need to know the size of your array. Then it is easy to find the largest element (and pointer to it)

int *max_el(const int * restrict p1, size_t size)
{
    const int *max = p1; 
    
    while(--size)
    {
        if(*max < *p1) max = p1;
        p1++;
    }
    return (int *)max;
}

or using your prototype:

int *max_el(const int * restrict p1, const int * restrict p2)
{
    const int *max = p1; 
    
    while(++p1 < p2)
        if(*max < *p1) max = p1;
    return (int *)max;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.