0

これは2つの行列を掛けるプログラムの一部です。2D配列を初期化する際のエラー

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; 

そして、この学校で私たちに教えているもの、現在あるので、私は、これらのエラー

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 

私は、Visual C++ 6.0(非常に古いバージョン)でこのコードを入力していますが取得しています。これらのエラーを取り除く手助けをしてください。前もって感謝します。

+0

あなたが変数と配列サイズを初期化するために許可されている場合、私は知らない... '' m1' m2' 'n1'と多次元配列の初期化前に定義された' n2'ですか?変数を実際の数値に置き換えてプログラムをテストしましたか? – ahitt6345

+0

変数が初期化される前に使用しています – stackptr

+0

ヒープを使用します。次のようなことをしてください:int ** first = new int * [m]; for(int i = 0; i user222031

答えて

0

あなたはこのような配列を初期化したいとき(値はコンパイル時間に知られている)constの値を使用する必要があります。たとえば :

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; 
} 
0

いくつかの配列を初期化するためにそれらの変数(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];