2017-05-03 11 views
-7

Arrayの要素をユーザーから取得して2次元配列を初期化するにはどうすればよいですか?2Dアレイの初期化?

+0

何を試しましたか、なぜ失敗しましたか? – Rakete1111

+2

何百もの以前の回答の中から検索を検討しましたか? – stark

+0

何をしているのか詳細を知りたい –

答えて

0

このように初期化するときは、2次元配列の境界を指定する必要があります。

int arr[][]int arr[row][col]に置き換えると、行と列の数が利用可能であることを前提として問題を解決できます。

次のコードは、有用であり得る:

#include <iostream> 
    using namespace std; 
    int main() 
    { 
     int row, col; 
     cout << "Number of rows : "; 
     cin >> row; 
     cout << "Number of columns : "; 
     cin >> col; 
     int arr[row][col]; 
     for (int i = 0; i < row; i++) { 
      for (int j = 0; j < col; j++) { 
       cout << "Enter value for row " << i << " column " << j << " : "; 
       cin >> arr[i][j]; 
      } 
     } 
     cout << "Elements of Array :" << endl; 
     for (int i = 0; i < row; i++) { 
      for (int j = 0; j < col; j++) { 
       cout << arr[i][j] << " "; 
      } 
      cout << endl; 
     } 
     return 0; 
    } 
+0

*** int arr [row] [col]; ***は無効ですC++。 C++はVLAを許可しません。いくつかのコンパイラはこれを拡張としてサポートしています。 – drescherjm

1

のC#とは異なり、++変数とアレイを初期化することができないC;値は修正する必要があります。 言語関連の問題と同様に、常に問題を回避する方法があります。 この場合、ポインタを使用して独自の動的配列を作成することをお勧めします。

#include <iostream> 
using namespace std; 
int main() 
{ 
    int row, col; 
    cout << "Number of rows : "; 
    cin >> row; 
    cout << "Number of columns : "; 
    cin >> col; 
    //init the pointer array 
    int **arr =new int*[row] ; 
    for (int i = 0; i < row; i++) 
    { 
     arr[i] = new int[col];// init the columns for each row 
     for (int j = 0; j < col; j++) 
     { 
      cout << "Enter value for row " << i << " column " << j << " : "; 
      cin >> arr[i][j]; 
     } 
    } 
    cout << "Elements of Array :" << endl; 
    for (int i = 0; i < row; i++) 
    { 
     for (int j = 0; j < col; j++) 
     { 
      cout << arr[i][j] << " "; 
     } 
    } 
    cout << endl; 
    return 0; 
} 
関連する問題