0

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;

}

0

2 Answers 2

1

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

Comments

0

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

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.