Home > Software design >  C : Find max value in array using 2 pointers (one for array, one for maximum)
C : Find max value in array using 2 pointers (one for array, one for maximum)

Time:12-14

I'm trying to print the max value typed in the array but it keeps giving me the last value that i entered even if its not the max value typed.

This is the exercise instructions:
Use pointers to determine the maximum value of an array of five typed doubles. Apply one pointer to the array elements and another to the auxiliary variable that holds the maximum value.

This is what i've done so far..

#include <stdio.h>
#include <stdlib.h>
#define array_double 5

int main() {
double m[array_double];
int c;
double *pArray;
double *pMax = 0;

printf("\nType values:\n");
for(c = 0; c < array_double; c  )
{
    scanf("%lf", &m[c]);
}


pArray = m;

for(c = 0; c < array_double; c  )
{
    if(pArray>pMax)
    {
        pMax = pArray;
    }
    pArray  ;
}

printf("\nMax value: %.2lf", *pMax);
return 0;

}

CodePudding user response:

You compare pointers instead of contents. The correct way to compare values is by dereferencing the pointers, e.g.

if (*pArray > *pMax) {
...
}

But for this to work, you must initialize pointer pMax too

pMax = m;

CodePudding user response:

The below modified program yields the output,

    #include <stdio.h>
#include <stdlib.h>
#define array_double 5

int main() {
double m[array_double];
int c;
double *pArray;
double *pMax = m;

printf("\nType values:\n");
for(c = 0; c < array_double; c  )
{
    scanf("%lf", &m[c]);
}


pArray = m;


for(c = 0; c < array_double; c  )
{
    if(*pArray>*pMax)
    {
        pMax = pArray;
    }
    pArray  ;
}

printf("\nMax value: %.2lf", *pMax);
return 0;
}

enter image description here

  • Related