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

C++自定义行列二维数组输入输出异常问题排查求助

问题分析与修复方案

核心问题

你遇到的问题根源在于在标准C++中,不能使用未初始化的变量定义静态数组的大小,而且代码的执行顺序完全搞反了:

  • 你先声明了int tom[rows][columns];,但此时rows和columns还没有被用户输入赋值,它们的值是内存里的随机垃圾值
  • 后续输入rows和columns后,数组的实际大小已经固定为之前垃圾值对应的大小,这导致你后续输入的元素写入了错误的内存位置,输出时自然出现重复的乱值

修复步骤

要解决这个问题,你需要调整代码顺序,并且选择支持动态大小的数组实现方式。这里提供两种常用方案:

方案1:使用动态内存分配(原生数组)

先获取用户输入的行数和列数,再动态创建二维数组,记得最后手动释放内存避免泄漏:

#include <iostream>
using namespace std;

int main() {
    int rows, columns;
    
    // 先获取行数和列数
    cout << "Size of array rows: ";
    cin >> rows;
    cout << "Size of array columns: ";
    cin >> columns;
    
    // 动态分配二维数组
    int** tom = new int*[rows];
    for (int i = 0; i < rows; ++i) {
        tom[i] = new int[columns];
    }
    
    // 输入元素
    for(int count1 = 0; count1 < rows; count1++) {
        for(int count2 = 0; count2 < columns; count2++) {
            cout << "Enter entry of row " << count1 << " and column " << count2 << ": ";
            cin >> tom[count1][count2];
        }
    }
    
    // 输出元素
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < columns; j++) {
            cout << tom[i][j] << endl;
        }
    }
    
    // 释放动态分配的内存
    for (int i = 0; i < rows; ++i) {
        delete[] tom[i];
    }
    delete[] tom;
    
    return 0;
}

方案2:使用std::vector(更安全简洁,推荐)

vector会自动管理内存,不需要手动释放,是C++中处理动态数组的首选方式:

#include <iostream>
#include <vector> // 必须包含vector头文件
using namespace std;

int main() {
    int rows, columns;
    
    cout << "Size of array rows: ";
    cin >> rows;
    cout << "Size of array columns: ";
    cin >> columns;
    
    // 创建rows行columns列的二维vector
    vector<vector<int>> tom(rows, vector<int>(columns));
    
    // 输入元素
    for(int count1 = 0; count1 < rows; count1++) {
        for(int count2 = 0; count2 < columns; count2++) {
            cout << "Enter entry of row " << count1 << " and column " << count2 << ": ";
            cin >> tom[count1][count2];
        }
    }
    
    // 输出元素
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < columns; j++) {
            cout << tom[i][j] << endl;
        }
    }
    
    return 0;
}

验证效果

运行修正后的代码,输入测试数据:

Size of array rows: 2
Size of array columns: 3
Enter entry of row 0 and column 0: 1
Enter entry of row 0 and column 1: 2
Enter entry of row 0 and column 2: 3
Enter entry of row 1 and column 0: 12
Enter entry of row 1 and column 1: 13
Enter entry of row 1 and column 2: 14

会得到期望的输出:

1
2
3
12
13
14

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:09:13