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

如何在C++中定义n行m列多维数组并通过For循环遍历赋值?

问题原因
  • 代码执行顺序错误:你在声明二维数组a[n][m]时,还没有通过cin读取n和m的取值,此时两个变量都是未初始化的随机值,编译器因此抛出未初始化警告。
  • 循环变量未初始化:两层for循环中的i和j都没有初始赋值为0,会导致遍历范围异常,甚至访问数组越界。
  • 非标准语法问题:C++国际标准并未支持变长数组(即数组长度用变量定义的写法),当前能编译通过是GCC的扩展特性,代码跨编译器兼容性差。
解决方案

方案1:调整执行顺序(仅兼容支持VLA扩展的编译器)

调整数组声明的位置到读取n、m之后,同时补全循环变量初始化,修正后代码如下:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n, m, x;
    cin>>n>>m; // 先读取行列数
    int a[n][m]; // 再声明数组
    for(int i=0; i<n ; i++) // i初始化为0
    {
        for(int j=0;  j<m ; j++) // j初始化为0
        {
            cout<<"Enter the values";
            cin>>x;
            a[i][j] = x;
        }
    }
    return 0;
}

方案2:使用标准C++容器vector(推荐,全编译器兼容)

用STL的vector替代原生数组,完全符合C++标准,不需要依赖编译器扩展,写法更安全:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n, m, x;
    cin>>n>>m;
    vector<vector<int>> a(n, vector<int>(m)); // 声明n行m列的二维数组
    for(int i=0; i<n ; i++)
    {
        for(int j=0;  j<m ; j++)
        {
            cout<<"Enter the values";
            cin>>x;
            a[i][j] = x;
        }
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:18:02