You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言数组排序检查代码输出异常/无输出问题排查求助

数组排序检查代码无输出问题排查

用户编写的C语言代码用于检查数组是否已排序,但运行时有时能输出正确结果,有时无任何输出,代码如下:

#include <stdio.h>

int ret(int[], int);

int main() {
    int n;

    scanf("%d", & n);

    int i;
    int a[n];

    for (i = 0; i < n; i++) {
        scanf("%d", & a[i]);
    }
    
    ret(a, n);

    return 0;
}

int ret(int a[], int n) {
    int i, c1 = 0, c2 = 0;

    if (a[n - 1] >= a[n - 2] && a[0] <= a[1]) {
        for (i = 0; i < n - 1; i++) {
            if (a[i] <= a[i + 1]) {
                c1++;
            }
        }

        if (c1 == n - 1) {
            puts("SORTED");
        } else {
            puts("NOTSORTED");
        }
    } else if (a[n - 1] <= a[n - 2] && a[0] >= a[1]) {
        for (i = 0; i < n - 1; i++) {
            if (a[i] >= a[i + 1]) {
                c2++;
            }
        }

        if (c2 == n - 1) {
            puts("SORTED");
        } else {
            puts("NOT SORTED");
        }
    }
    
    return 0;
}

问题根源

  1. 边界情况未处理:当输入的n=1时,数组只有一个元素,代码中访问a[n-2]即a[-1],属于数组越界访问,触发未定义行为,可能导致程序无输出甚至崩溃。
  2. 逻辑覆盖不全:当数组既不是升序开头也不是降序开头时(比如乱序数组[1,3,2]),两个if/else if条件都不满足,函数ret直接返回,没有任何输出语句执行。

修复方案

  1. 优先处理n<=1的情况:单个元素本身就是有序的,直接输出SORTED。
  2. 重新梳理检查逻辑:先判断是否为升序数组,再判断是否为降序数组,只要满足其一就输出SORTED,否则输出NOT SORTED,确保所有情况都有输出。

修复后的代码:

#include <stdio.h>

void checkSorted(int[], int);

int main() {
    int n;
    scanf("%d", &n);

    int a[n];
    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    
    checkSorted(a, n);
    return 0;
}

void checkSorted(int a[], int n) {
    // 处理单个元素的情况
    if (n <= 1) {
        puts("SORTED");
        return;
    }

    int isAscending = 1;
    int isDescending = 1;

    // 检查是否升序
    for (int i = 0; i < n - 1; i++) {
        if (a[i] > a[i + 1]) {
            isAscending = 0;
            break;
        }
    }

    // 检查是否降序
    if (!isAscending) {
        for (int i = 0; i < n - 1; i++) {
            if (a[i] < a[i + 1]) {
                isDescending = 0;
                break;
            }
        }
    }

    if (isAscending || isDescending) {
        puts("SORTED");
    } else {
        puts("NOT SORTED");
    }
}

内容的提问来源于stack exchange,提问作者Bharath R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:05:28