【问题标题】:How to pass a 2D array to a function with the user defining the number of columns?(C++)如何将二维数组传递给用户定义列数的函数?(C++)
【发布时间】:2015-11-23 21:27:41
【问题描述】:

举例说明我遇到的问题。我做了这个简单的程序,我试图阅读一堆教程并在谷歌搜索我的问题,但我就是不明白。

#include<iostream>
using namespace std;

void noobFunction( int col , int table[][col]){ // compile error
   table[0][0] = 2;
   cout << table[0][0];
}

int main() {
   cout << "Enter the number of rows in the 2D array:  ";
   int row;
   cin >> row;

   cout << "Enter the number of columns in the 2D array:  ";
   int col;
   cin >> col; 

   int table[lin][col];

   noobFunction(col, table); 

   return 0;
}

【问题讨论】:

标签: c++ arrays


【解决方案1】:

运行时大小的数组不是 C++ 标准功能。如果您想要动态二维数组,请使用std::vector&lt;std::vector&lt;int&gt;&gt;

std::vector<std::vector<int>> table(lin, std::vector<int>(col));;

并将你的函数定义为:

void noobFunction(std::vector<std::vector<int>> &table) {
  // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多