传递具有可变大小的2D数组

时间:2013-10-28 07:23:53

标签: c++ arrays

我正在尝试将2D数组从函数传递到另一个函数。但是,数组的大小不是恒定的。大小由用户决定。

我试图研究这个,但没有多少运气。大多数代码和解释都是针对数组的恒定大小。

在我的函数A中我声明了变量然后我稍微操纵它,然后它必须传递给函数B

void A()
{
      int n;
      cout << "What is the size?: ";
      cin >> n;

      int Arr[n-1][n];

      //Arr gets manipulated here

      B(n, Arr);
}

void B(int n, int Arr[][])
{
    //printing out Arr and other things

}

3 个答案:

答案 0 :(得分:11)

如果您想要动态大小的数组,请使用std::vector

std::vector<std::vector<int>> Arr(n, std::vector<int>(n - 1));
B(Arr);

void B(std::vector<std::vector<int>> const& Arr) { … }

答案 1 :(得分:3)

数组大小需要保持不变。或者,您可以使用std::vector<std::vector<int>>来表示动态2D数组。

答案 2 :(得分:3)

C ++不支持可变长度数组。 拥有C99并仅将其编译为C,您可以像这样传递数组:

#include <stdio.h>

void B(int rows, int columns, int Arr[rows][columns]) {
    printf("rows: %d, columns: %d\n", rows, columns);
}

void A() {
    int n = 3;
    int Arr[n-1][n];
    B(n-1, n, Arr);
}


int main()
{
    A();
    return 0;
}

注意:在函数周围放置extern“C”{}并不能解析C ++       与C99不兼容:

  g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2:
  error: use of parameter ‘rows’ outside function body
  error: use of parameter ‘columns’ outside function body
  warning: ISO C++ forbids variable length array
相关问题