简体   繁体   English

如何在用户定义列数的情况下将2D数组传递给函数?(C ++)

[英]How to pass a 2D array to a function with the user defining the number of columns?(C++)

To exemplify what I am having trouble with. 举例说明我遇到的麻烦。 I made this simple program, I tried to read a bunch of tutorials and search my trouble in google but I just did not understand. 我做了这个简单的程序,我试图阅读一堆教程并在Google中搜索我的麻烦,但我只是不明白。

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

Runtime sized arrays are not a C++ standard feature. 运行时大小的数组不是C ++标准功能。 If you want dynamic 2D arrays use a std::vector<std::vector<int>> : 如果要动态2D数组,请使用std::vector<std::vector<int>>

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

and define your function as: 并将您的函数定义为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM