2017-05-03 177 views
-7

如何通过从用户数组中获取元素来初始化2d数组?2D阵列初始化?

#include <iostream> 
using namepace std; 
int main() 
{ 
    int row, col; 
    int arr[][]; 
    for (int i = 0; i < row; i++) { 
     for (int j = 0; j < col; j++) { 
      cout << "Elements of Array :" << ' '; 
      cin >> arr[i][j]; 
     } 
    } 
    return 0; 
} 
+0

你有什么试过,为什么你失败了? – Rakete1111

+2

您是否考虑过在数百个之前的答案中搜索? – stark

+0

需要你在做什么的更多细节 –

回答

0

以这种方式进行初始化时,必须指定2D数组的边界。

更换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; 
}