c - 查找大于和小于数组中的数字

标签 c pass-by-reference

#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++;
    }
}

需要帮助了解为什么它只返回最小值和最大值的随机数。引用传递可能是它搞砸的原因,但我不知道我能做些什么来修复它。

最佳答案

您的代码有未定义的行为。

由于operator precedence (++ 的优先级高于取消引用运算符 *)

* min++;

翻译为

*(min++);

你需要的是

(*min)++;

更好的是,更改您的函数以接受引用类型并让您的生活更轻松。

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++;
    }
}

此外,请确保初始化 max1min1。否则,您的代码会使用未初始化变量的值,这会导致未定义的行为。

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

关于c - 查找大于和小于数组中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57619790/

相关文章:

C - Header 中的函数实现是否应该使用 extern/inline/static?

c++ - f(const string &) 和 f(const string ) 之间有什么区别吗?

java - 传递参数与从函数返回参数

C:动态分配时通过引用传递

C语言 : Header inclusion makes unexpected behavior

c - 二进制数据打印不正确

c - 如何在键盘输入时立即停止C while循环而不继续下一步?

c++ - 线程在给定时隙内执行的指令数是否最少?

c++ - 从对象调用成员对象,错误: initial value of reference to non-const must be an lvalue

powershell - 如何在 Invoke-Command -ArgumentList 中通过引用传递变量