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

C语言实现边拷贝数组边排序时仅拷贝前2个元素问题求解

你当前贴出的代码仅在原数组number上完成了降序排序,没有对声明的number2数组做任何拷贝操作,没有实现拷贝同时排序的需求。你提到的仅能拷贝前2个元素就停止的问题,通常是整合逻辑时循环边界错误、变量复用冲突或者数组越界导致的。

以下是修复后的完整实现,采用先全量拷贝、再对目标数组排序的逻辑,兼容你原有使用的选择排序写法:

#include <stdio.h>
#include <stdlib.h>
int main ()
{
    int number[30];
    int number2[30];
    int i, j, a, n;
    printf("Enter the value of N\n");
    scanf("%d", &n);
    // 输入合法性校验,避免数组越界
    if(n > 30 || n < 1) {
        printf("N should be between 1 and 30\n");
        system("pause");
        return 0;
    }
    printf("Enter the numbers \n");
    for (i = 0; i < n; ++i)
        scanf("%d", &number[i]);
    // 完整拷贝原数组到目标数组
    for (i = 0; i < n; ++i)
        number2[i] = number[i];
    // 仅对目标数组做降序排序,不修改原数组内容
    for (i = 0; i < n; ++i) 
    {
        for (j = i + 1; j < n; ++j) 
        {
            if (number2[i] < number2[j]) 
            {
                a = number2[i];
                number2[i] = number2[j];
                number2[j] = a;
            }
        }
    }
    printf("The original array is:\n");
    for (i = 0; i < n; ++i) 
    {
        printf("%d ", number[i]);
    }
    printf("\nThe copied and sorted array is:\n");
    for (i = 0; i < n; ++i) 
    {
        printf("%d\n", number2[i]);
    }
    system("Pause");
    return 0;
}

导致你之前拷贝逻辑异常的常见原因:

  • 拷贝逻辑错误复用了排序内层循环的j变量作为计数器,篡改了排序循环的边界值,导致循环提前终止
  • 拷贝循环的终止条件被误写为固定值(例如i < 2),没有使用动态输入的n作为边界
  • 输入的n值超过数组定义的长度上限30,触发数组越界导致程序异常退出
  • 没有对输入的n做合法性校验,输入非正整数时会导致循环逻辑完全异常

内容的提问来源于stack exchange,提问作者apostolos paliouras

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:06:03