0
#include<stdio.h>

void find(int a[], int n, int *min, int *max){
    int tmp, i, j;
    for(i = 0; i < n; i++){
        for(j = i + 1; j < n; j++){
            if(a[i] < a[j]){
                tmp = a[i];
                a[i] = a[j];
                a[j] = tmp;
            }
        }
    }
    *max = *a;
    *min = *(a + n);
    
}

int main(){
    int a[100];
    int n, *min, *max;
    printf("husnegtiinn elementiin toog oruul: ");
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
        scanf("%d", &a[i]);
    }
    find(a, n, min, max);
    printf("ih ni : %d \nbaga ni : %d", *max, *min);
    
}

I am trying to sort the array from user and get the min and max values in those pointers. I am having hard time figuring out how to pass pointers through functions. Am I missing something here?

2
  • *(a + n); is outside of the initialized elements in the array. *(a + n - 1) (or simpler a[n-1]) is the last element to which you assigned values. Commented Dec 18, 2022 at 14:51
  • The pointers min and max are not initialized, so it's illegal to dereference and assign values like *max = *a. Commented Dec 18, 2022 at 14:52

1 Answer 1

2
  • *(a + n) is outside of the initialized elements in the array. *(a + n - 1) (or simpler a[n-1]) is the last element to which you assigned values.
  • min and max should not be int*s but ints.

Example:

#include<stdio.h>

void find(int a[], int n, int *min, int *max){
    if(n < 1) return;

    for(int i = 0; i < n; i++){
        for(int j = i + 1; j < n; j++){
            if(a[i] < a[j]){
                int tmp = a[i];
                a[i] = a[j];
                a[j] = tmp;
            }
        }
    }
    *max = a[0];
    *min = a[n - 1]; // the last element
    
}

int main(){
    int a[100];
    int n, min, max; // corrected types
    printf("husnegtiinn elementiin toog oruul: ");

    if(scanf("%d", &n) != 1 || n < 1 || n > 100) return 1;

    for(int i = 0; i < n; i++){
        scanf("%d", &a[i]);
    }
    find(a, n, &min, &max); // take the addresses of `min` and `max`
    printf("ih ni : %d \nbaga ni : %d", max, min);
}
Sign up to request clarification or add additional context in comments.

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.