Use the pointer to find the maximum and minimum values

Asked 2 years ago, Updated 2 years ago, 27 views

int maxmin(int ar[]) 
{

    int *px;
    int min = 0, max = 0;
    for (px = ar; px < (sizeof(ar)/sizeof(int)); px++) 
    {
        if (*px < min) 
        {
            min = *px;
        }
        if (*px > max) 
        {
            max = *px;
        }
    }
    return max-min;
}

int main() 
{

    int N,ar[100],sum=0;

    int *px,*py;

    scanf("%d", &N);
    for (px = ar; px < ar + N; px++) 
    {
        for (py = ar; *(py - 1); py++)
        {
            scanf("%d", py);
        }
        for (py = ar;sizeof(ar)/sizeof(int)-1; py++)
        {
            sum = maxmin(py);
        }
        printf("%d", sum);
    }
}

As a result of debugging, the for statement in the int maxmin() function does not work, but (sizeof(ar)/sizeof(int) is this part wrong?

c

2022-09-22 17:54

1 Answers

Rather than being wrong, it seems necessary to understand what is called a pointer.

The pointer size is 4 bytes (32 bits) for 32-bit os. You can't get the result you want in the same way as the question.

Perhaps the answer you want is, "Can I know the number of arrays that the pointer refers to by going beyond the pointer of the array?" Unfortunately, I don't know. Usually, the number of arrays is also handed over as a factor. In other words, take the number as a variable in the maxmin function.

As an admonition, c++ recommends using vector instead of array and can provide macros such as __countof. However, in c, the most recommended method is to exceed the number of arrays with a factor.


2022-09-22 17:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.