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

C语言程序scanf输入后异常退出问题求助及代码排查

问题描述

本人具备C++开发经验,但刚接触C语言。编写的程序需通过scanf获取用户输入的数组长度N和操作变量t,目前输入N后程序会短暂延迟随即退出,怀疑是输入逻辑设置问题。附上当前代码,希望先解决输入问题,再排查sum等函数及其他逻辑问题。预期能先排查sum等函数是否正常,再处理第6、7个case的逻辑。

// Input: The first line of the input contains an integer N and t (3 <= N <= 200000; 1 <= t <= 7)
// Output: For each test case, output the required answer based on the value of t.

#include <stdio.h>

int main(){
    // Initialize integer N and t for inputting.
    int N, t;
    
    scanf("%d", N);
    scanf("%d", t);
    
    // Initialize array for inputting components.
    int A[N];
    for(int c = 0; c < N; c++){
        scanf("%d", A[c]);
    }
    
    switch(t){
        // Print 7, regardless of array A's contents
        case 1:
            printf("%d\n, 7");
        
        // Print "Bigger" if A[0] > A[1] or "Equal" if A[0] == A[1]. Otherwise, print "Smaller".
        case 2:
            if(A[0] > A[1]){
                printf("%d\n, Bigger");
            }
            else if(A[0] == A[1]){
                printf("%d\n, Equal");
            }
            else{
                printf("%d\n, Smaller");
            }
        
        // Print the median of the first three indexes of the A array.
        case 3: 
            printf("%d\n, (A[0]+A[1]+A[2])/2");
        
        // Print the sum of all integers in A.
        case 4:
            printf("%d\n, Sum(A, N)");
        
        // Print the sum of all EVEN integers in A.
        case 5:
            printf("%d\n, evSum(A, N)");
        
        // Apply %26 to each integer in the A array, map integers from 0-25 to the alphabet,
            // and print the new sequence of characters as a string.
        case 6:
            // Figuring this one out
            printf("\nStub");
        
        // Start from index i = 0; Jump to index i = A[i]; If the current index is outside
            // the valid bound from 0 to N-1, print "Out" and exit. Else, if the
            // current index is the index N-1, print "Done" and exit, otherwise go back
            // to step b. If doing this leads to an infinite loop, print "Cyclic" and exit.
        case 7:
            // Figuring this one out
            printf("\nStub");
    }
    
    return 0;
}

// Integer function that returns the sum of all the integers in the inputted array.
// Apparently, you also need to add the length of the array externally, since it wont just let me use 'N'.
int sum(int* array[], int arrayLength){
    int k = 0;
    for(int o = 0; o < arrayLength; o++){
        k = k + *array[o];
    }
    return k;
}

// Integer function that returns the sum of all the even integers in the inputted array.
// To check if an integer is even, it checks if the modulo of 2 for the integer is equal to 0.
// Apparently, you also need to add the length of the array externally, since it wont just let me use 'N'.
int evSum(int* array[], int arrayLength){
    int l = 0;
    for(int m = 0; m < arrayLength; m++){
        if(*array[m] % 2 == 0){
            l = l + *array[m];
        }
    return l;
    }
}
问题修复步骤

一、解决输入崩溃问题

这是程序退出的核心原因:

  • scanf要求传入变量的地址,代码直接传变量值属于非法内存访问,修改如下:
    scanf("%d", &N);
    scanf("%d", &t);
    // 数组元素输入同理:
    scanf("%d", &A[c]);
    
  • 优化输入逻辑:题目要求第一行输入N和t,可合并为一次读取,减少输入步骤:
    scanf("%d %d", &N, &t);
    

二、修复sum与evSum函数

  1. 参数类型错误:函数定义中int* array[]是指针数组,而传入的是普通数组,应改为普通指针/数组参数:
    int sum(int array[], int arrayLength)
    // 等价写法:int sum(int* array, int arrayLength)
    
    evSum函数同理修改参数。
  2. 函数调用大小写错误:C语言区分大小写,main中Sum(A, N)应改为sum(A, N)。
  3. evSum返回位置错误:return语句放在for循环内部,导致第一次循环就直接返回,需移到循环外:
    int evSum(int array[], int arrayLength){
        int l = 0;
        for(int m = 0; m < arrayLength; m++){
            if(array[m] % 2 == 0){
                l += array[m];
            }
        }
        return l; // 移到循环外
    }
    
  4. 函数声明缺失:C语言要求函数先声明再使用,在main前添加函数原型:
    int sum(int array[], int arrayLength);
    int evSum(int array[], int arrayLength);
    

三、修复switch-case逻辑

  1. 缺少break语句:每个case执行完后会继续执行后续case,必须添加break;终止:
    case 1:
        printf("7\n");
        break;
    case 2:
        // ...逻辑...
        break;
    // 所有case同理添加break
    
  2. printf格式错误:
    • case1中printf("%d\n, 7");无对应参数,直接输出字符串即可:printf("7\n");
    • case2中不需要%d,直接输出对应字符串:printf("Bigger\n");
    • case4、5需要调用函数并输出结果:
      case4:
          printf("%d\n", sum(A, N));
          break;
      case5:
          printf("%d\n", evSum(A, N));
          break;
      
    • case3的中位数计算错误:(A[0]+A[1]+A[2])/2不是中位数,需先排序前三个数取中间值,示例:
      case3: {
          int temp[3] = {A[0], A[1], A[2]};
          // 冒泡排序前三个数
          for(int i=0; i<2; i++){
              for(int j=i+1; j<3; j++){
                  if(temp[i] > temp[j]){
                      int swap = temp[i];
                      temp[i] = temp[j];
                      temp[j] = swap;
                  }
              }
          }
          printf("%d\n", temp[1]);
          break;
      }
      

四、其他优化建议

  • 变长数组风险:int A[N];在N=200000时会耗尽栈空间,建议用动态内存分配:
    #include <stdlib.h> // 需包含该头文件
    int* A = malloc(N * sizeof(int));
    // 使用完后释放:
    free(A);
    
修复后示例代码
#include <stdio.h>
#include <stdlib.h>

// 函数原型声明
int sum(int array[], int arrayLength);
int evSum(int array[], int arrayLength);

int main(){
    int N, t;
    // 读取N和t
    scanf("%d %d", &N, &t);
    
    // 动态分配数组
    int* A = malloc(N * sizeof(int));
    if(A == NULL){
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // 读取数组元素
    for(int c = 0; c < N; c++){
        scanf("%d", &A[c]);
    }
    
    switch(t){
        case 1:
            printf("7\n");
            break;
        case 2:
            if(A[0] > A[1]){
                printf("Bigger\n");
            }
            else if(A[0] == A[1]){
                printf("Equal\n");
            }
            else{
                printf("Smaller\n");
            }
            break;
        case 3: {
            int temp[3] = {A[0], A[1], A[2]};
            // 冒泡排序前三个数
            for(int i=0; i<2; i++){
                for(int j=i+1; j<3; j++){
                    if(temp[i] > temp[j]){
                        int swap = temp[i];
                        temp[i] = temp[j];
                        temp[j] = swap;
                    }
                }
            }
            printf("%d\n", temp[1]);
            break;
        }
        case 4:
            printf("%d\n", sum(A, N));
            break;
        case 5:
            printf("%d\n", evSum(A, N));
            break;
        case 6:
            printf("\nStub");
            break;
        case 7:
            printf("\nStub");
            break;
        default:
            printf("Invalid t value\n");
            break;
    }
    
    // 释放动态内存
    free(A);
    return 0;
}

int sum(int array[], int arrayLength){
    int k = 0;
    for(int o = 0; o < arrayLength; o++){
        k += array[o];
    }
    return k;
}

int evSum(int array[], int arrayLength){
    int l = 0;
    for(int m = 0; m < arrayLength; m++){
        if(array[m] % 2 == 0){
            l += array[m];
        }
    }
    return l;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:22:01