Search code examples
cpass-by-reference

Finding numbers greater and less than in array


#include <stdio.h>
#define SIZE 10
void function(int array[], int size, int compare, int* min, int* max);

int main() {
    int max1, min1, n, m, array1[SIZE];
    printf("Please enter an array size: ");
    scanf("%d", &n);
    printf("Enter numbers for array:");
    for (int i = 0; i < n; i++) {
        printf("enter number %d", i + 1);
        scanf("%d", &array1[i]);
    }
    printf("Enter a number to be compared:");
    scanf("%d", &m);
    function(array1, n, m, &min1, &max1);
    printf("There are %d numbers less than %d and there are %d numbers greater than %d",min1, m, max1, m);
}

void function(int array[], int size, int compare, int *min, int *max) {
    for (int i = 0; i < size; i++) {
        if (array[i] < compare)* min++;
        if (array[i] > compare)* max++;
    }
}

Need help on why it just returns random numbers for the min and max. The pass by reference is probably what is screwed it up, but I don't know what I can do to fix it.


Solution

  • Your code has undefined behavior.

    Due to operator precedence (++ has a higher precedence than the dereference operator *)

    * min++;
    

    is translated as

    *(min++);
    

    What you need is

    (*min)++;
    

    Better yet, change your function to accept reference types and make your life easier.

    void function(int array[], int size, int compare, int& min, int& max) {
        for (int i = 0; i < size; i++) {
            if (array[i] < compare) min++;
            if (array[i] > compare) max++;
        }
    }
    

    Also, make sure to initialize max1 and min1. Otherwise, your code uses values of uninitialized variables, which causes undefined behavior.

    int max1 = 0;
    int min1 = 0;
    int n, m, array1[SIZE];