简体   繁体   中英

How can I solve this problem with pointers in C?

In the code below, I'm trying to implement a function that finds the maximun and minimun of a given array. But I was trying to use a different approach. I was trying to change the memory adress of the pointers for the maximum and minimum.

Why this is not working? Should I use pointers to pointers for solving this problem?

#include <stdio.h>
#define M 5

void maxMin(int *v, int N, int *max, int *min){
    int i;
    printf("%d\n",*v);
    printf("%d\n",*max);
    for(i = 0; i < M; i++){
        if(*max < *(v+i)){
            max = (v+i);
        }
        if(*min > *(v+i)){
            min = (v+i);
        }
    }
}

int main(){
    int v[M] = {1, 3, 5, 7, 8}, *max=v, *min=v;
    maxMin(v, M, max, min);

    printf("MAX %d\n", *max);
    printf("MIN %d\n", *min);
    return 0;
}

You should use double pointers because passing it like this will copy the value of the pointers.

void maxMin(int *v, int N, int **max, int **min){
    int i;
    int minVal = *v;
    int maxVal = *v;
    for(i = 0; i < M; i++){
        if(maxVal < *(v+i)){
            maxVal = *(v+i);
            *max = (v+i);
        }
        if(minVal > *(v+i)){
            minVal = *(v+i);
            *min = (v+i);
        }
    }
}

Then you call the function like this.

maxMin(v, M, &max, &min);

The rest stays the same.

The only reason why you need to use pointers here, is because you wish to return both min and max, but a function only has one return value. Therefore, you have to return them through the parameters.

#include <stdio.h>
#define M 5

void maxMin(size_t n, const int v[n], int *max, int *min)
{
  *max = v[0];
  *min = v[0];

  for(size_t i = 1; i < n; i++)
  {
    if(*max < v[i])
    {
      *max = v[i];
    }
    if(*min > v[i]){
      *min = v[i];
    }
  }
}

int main (void)
{
  int v[M] = {1, 3, 5, 7, 8};
  int max;
  int min;

  maxMin(M, v, &max, &min);

  printf("MAX %d\n", max);
  printf("MIN %d\n", min);
  return 0;
}

(Returning two pointers that point at the max and min elements would be a weird interface - in that case you would rather return the indices where max and min could be found.)

You are passing the value(that is the starting address of array) stored in pointers max and min to the function maxMin() with maxMin(v, M, max, min) . What this means is that the pointer variables min and max in main() are related to min and max pointer variables in maxMin() argument list. So any change done to these variables in maxMin() will not be reflected in main() .

What you need to do is pass the address of min and max variables and update the values of the *min and *max in the function maxMin (See Petar Velev answer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM