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

构建2n阶输入矩阵时打印异常问题求助

问题分析与修复

问题根源

你需要构建的是2n * 2n阶矩阵,但代码里错误地将数组定义为(2*n - 1) * (2*n - 1)的大小,后续的输入、打印循环却都按照2n的范围执行,这直接触发了数组越界访问的未定义行为,导致输出异常。

修复后的代码

#include<stdio.h>
int main() {
    printf("Insert n:\n");
    int n = 0;
    scanf("%d", &n);
    printf("Insert the elements of the matrix %d * %d\n", 2*n, 2*n);
    // 修正矩阵大小为目标的2n*2n
    int mat[2 * n][2 * n];
    for (int i = 0; i < 2 * n; i++) {
        for (int j = 0; j < 2 * n; j++) {
            scanf("%d", &mat[i][j]);
        }
    }
    for (int i = 0; i < 2 * n; i++) {
        for (int j = 0; j < 2 * n; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
    return 0;
}

验证效果

当输入n=1,并输入元素1 2 3 4时,会正常输出:

Insert n:
1
Insert the elements of the matrix 2 * 2
1 2 3 4
1 2 
3 4 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:39:19