Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 313
John0651 Avatar asked Mar 04 '23 13:03

John0651


2 Answers

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];
like image 172
R Sahu Avatar answered Mar 14 '23 21:03

R Sahu


min1 and max1 are never initialized, containing garbage values. function then increments them, arriving at slightly different garbage values - but still garbage.

Your program exhibits undefined behavior by way of accessing an uninitialized object.

like image 28
Igor Tandetnik Avatar answered Mar 14 '23 21:03

Igor Tandetnik