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