John
John

Reputation: 3

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;
}

Upvotes: 0

Views: 1069

Answers (3)

0___________
0___________

Reputation: 67546

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;
}

Upvotes: 0

4386427
4386427

Reputation: 44274

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;    
}

Upvotes: 1

mzimmers
mzimmers

Reputation: 902

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?

Upvotes: 0

Related Questions