C++ 初始化二维数组时出错

C++ 初始化二维数组时出错,c++,arrays,visual-c++,multidimensional-array,matrix-multiplication,C++,Arrays,Visual C++,Multidimensional Array,Matrix Multiplication,这是我的程序的一部分,用来乘2个矩阵 int m1, m2, n1, n2; int first[m1][n1], second[m2][n2], result[m1][n2]; cout<<"Please enter no.of rows and columns of the 1st Matrix, respectively :"; cin>>m1>>n1; intm1、m2、n1、n2; int第一[m1][n1],第二[m2][n2],结果[m1][n

这是我的程序的一部分,用来乘2个矩阵

int m1, m2, n1, n2;
int first[m1][n1], second[m2][n2], result[m1][n2];
cout<<"Please enter no.of rows and columns of the 1st Matrix, respectively :";
cin>>m1>>n1;
intm1、m2、n1、n2;
int第一[m1][n1],第二[m2][n2],结果[m1][n2];
coutm1>>n1;
我得到了这些错误

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2057: expected constant expression
error C2087: '<Unknown>' : missing subscript
error C2133: 'first' : unknown size
错误C2057:应为常量表达式
错误C2466:无法分配常量大小为0的数组
错误C2057:应为常量表达式
错误C2087:'':缺少下标
错误C2133:“第一个”:未知大小

我在Visual C++ 6(非常旧的版本)中输入这个代码,因为这是目前在学校教给我们的。请帮我摆脱这些错误。提前感谢。

在使用这些变量初始化某些数组之前,必须为这些变量(m1、m2、n1、n2)分配一些数字。当您不给它们一些值时,最初它们是0。显然,您无法创建大小为0的数组,而且它是符合逻辑的。数组的大小是常量,而大小为0的数组则没有意义

也许你需要试试这样的东西:

int m1, m2, n1, n2;

cout << "Please enter no.of rows and columns of the 1st Matrix, respectively :";
cin >> m1 >> n1;

cout << "Please enter no.of rows and columns of the 2st Matrix, respectively :";
cin >> m2 >> n2;

int first[m1][n1], second[m2][n2], result[m1][n2];
intm1、m2、n1、n2;
cout>m1>>n1;
cout>m2>>n2;
int第一[m1][n1],第二[m2][n2],结果[m1][n2];

当您想要初始化这样的数组时,必须使用常量值(这些值在编译时是已知的)。 例如:

const int r = 1, c = 2;
int m[r][c];
但是,在您的情况下,您不知道编译期间的大小。所以你必须创建一个动态数组。 下面是一个示例片段

#include <iostream>

int main()
{
    int n_rows, n_cols;
    int **first;
    std::cout << "Please enter no.of rows and columns of the 1st Matrix, respectively :";
    std::cin >> n_rows >> n_cols;

    // allocate memory
    first = new int*[n_rows]();
    for (int i = 0; i < n_rows; ++i)
        first[i] = new int[n_cols]();

    // don't forget to free your memory!
    for (int i = 0; i < n_rows; ++i)
        delete[] first[i];
    delete[] first;

    return 0;
}
#包括
int main()
{
int n_行,n_列;
int**第一;
标准::cout>n_行>>n_列;
//分配内存
第一个=新的整数*[n_行]();
对于(int i=0;i
我不知道是否允许您使用变量初始化数组大小。。。多维数组初始化之前是否定义了m1和n2?您是否通过用实际数字替换变量来测试程序?您正在使用初始化堆之前的变量。这样做:int**first=newint*[m];对于(int i=0;i