传递具有可变大小的 2D 数组
Passing 2D array with variable Size
>我正在尝试将 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
}
如果需要动态大小的数组,请使用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) { … }
数组大小需要恒定。或者,您可以使用std::vector<std::vector<int>>
来表示动态 2D 数组。
C++不支持
可变长度数组。使用 C99 并仅编译为 C,您可以像这样传递数组:
#include <stdio.h>
void B(int rows, int columns, int Arr[rows][columns]) {
printf("rows: %d, columns: %dn", rows, columns);
}
void A() {
int n = 3;
int Arr[n-1][n];
B(n-1, n, Arr);
}
int main()
{
A();
return 0;
}
注意:在函数周围放置外部"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
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 使用指针算法修改函数中的 2D 数组
- 在C++中初始化和打印 2D 数组
- 有没有办法使用输入的维度初始化 2d 数组中的所有项目而不循环C++?
- C++ 2D 数组写入多个位置
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 如何从initializer_list初始化 2D 数组
- 交换函数不是在 C++ 中交换 2D 数组的元素