构建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
相关产品推荐
相关产品推荐

