While solving the problem of using double pointer variables, I had a question!!

Asked 2 years ago, Updated 2 years ago, 74 views

#include<stdio.h>

void MaxAndMin(int * arr,int size,int **mxptr,int **mnptr)
{
    int * max,* min;
    int i;
    *max=*min=arr[0];
    for(i=0;i<size;i++)
    {
        if(*max<arr[i])
            *max=arr[i];
        if(*min>arr[i])
            *min=arr[i];
    }
    *mxptr=max;
    *mnptr=min;
}

int main(void)
{
    int *maxPtr;
    int *minPtr;
    int arr[5];
    int i;

    for(i=0;i<sizeof(arr)/sizeof(int);i++)
    {
        printf ("Enter an integer %d:",i+1);
        scanf("%d",&arr[i]);
    }
    MaxAndMin(arr,sizeof(arr)/sizeof(int),&maxPtr,&minPtr);
    printf("%d %d",*maxPtr,*minPtr);
    return 0;
}

The code here and

#include<stdio.h>

void MaxAndMin(int * arr,int size,int **mxptr,int **mnptr)
{
    int * max,* min;
    int i;
    max=min=&arr[0];
    for(i=0;i<size;i++)
    {
        if(*max<arr[i])
            max=&arr[i];
        if(*min>arr[i])
            min=&arr[i];
    }
    *mxptr=max;
    *mnptr=min;
}

int main(void)
{
    int *maxPtr;
    int *minPtr;
    int arr[5];
    int i;

    for(i=0;i<sizeof(arr)/sizeof(int);i++)
    {
        printf ("Enter an integer %d:",i+1);
        scanf("%d",&arr[i]);
    }
    MaxAndMin(arr,sizeof(arr)/sizeof(int),&maxPtr,&minPtr);
    printf("%d %d",*maxPtr,*minPtr);
    return 0;
}

The difference between these codes is that the MaxAndMin function uses *min and min in the for statement, respectively The above code doesn't seem to be a big problem, but I want to know why the above code doesn't work properly while the lower one doesn't work!! (FYI, the code is a code that receives 5 integers and finds the minimum value of the maximum value.) I know a lot of other ways, so I'd appreciate it if you could find the wrong part in this way.)

pointer double call-by-reference

2022-09-22 19:02

1 Answers

In the above code, max and min are pointer variables that point to address values, but no address of any variable is assigned. Therefore, assigning arr[0] to the variable pointed by the pointer variable inevitably results in an access violation error, provided that max and min are initialized to NULL.


2022-09-22 19:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.