LIFE
LIFE

Reputation: 31

print max with pointer

#include <stdio.h>

void MaxandMin(int * arr, int len,int **p1, int **p2);

int main(void)
{
    int arr[5] = {1,3,5,2,4};
    int len = sizeof(arr) / sizeof(int);
    int * maxPtr;
    int * minPtr;
    int ** dptr1 = &minPtr;
    int ** dptr2 = &maxPtr;

    MaxandMin(arr,len, dptr1, dptr2);

    printf("max is %d, min is %d\n", *maxPtr, *minPtr);

    return 0;   
}

void MaxandMin(int * arr, int len, int **p1, int **p2)
{
    int * max;
    int * min;
    max = min = &arr[0];

    for (int i = 0; i < len; len++)                     
    {
        if (*max < *(arr + i))
            max = (arr + i);
        if (*min > *(arr + i))
            min = (arr + i);
    }

    *p1 = max;
    *p2 = min;
}

I want to print max and min number in the array arr. I think there's nothing wrong, but I can't see any output. I have tried some more expression of pointer and addresses. So may I ask how I can see output of this program in this situation? thank you.

Upvotes: 1

Views: 54

Answers (1)

tbrk
tbrk

Reputation: 1299

Increment i and not len:

for (int i = 0; i < len; i++)
{ ... }

*p1 = min;
*p2 = max;

(Also, the assignments to *p1 and *p2, are mixed up).

A few other tips

  • You can just write max = min = arr.
  • You don't need dptr1 and dptr2: MaxandMin(arr,len, &minPtr, &maxPtr)

Upvotes: 2

Related Questions