将具有可变边界的2d数组传递给函数
passing 2d array with variable boundaries to a function
我有一个array
的边界是由另一个变量(不是常量)定义的:
int max = 10;
int array[max][max];
现在我有一个使用array
的函数,但我不知道如何将数组传递给函数。我该怎么做呢?
所以为了更清楚,我如何使这个工作(我想使用类,但是变量max
是由用户输入定义的,所以我不能使数组成为类的成员,因为max
必须是常量)
void function (int array[max][max])
{
}
#include <iostream>
using namespace std;
int main() {
int** Matrix; //A pointer to pointers to an int.
int rows,columns;
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> columns;
Matrix = new int*[rows]; //Matrix is now a pointer to an array of 'rows' pointers.
for(int i=0; i<rows; i++) {
Matrix[i] = new int[columns]; //the i place in the array is initialized
for(int j = 0;j<columns;j++) { //the [i][j] element is defined
cout<<"Enter element in row "<<(i+1)<<" and column "<<(j+1)<<": ";
cin>>Matrix[i][j];
}
}
cout << "The matrix you have input is:n";
for(int i=0; i < rows; i++) {
for(int j=0; j < columns; j++)
cout << Matrix[i][j] << "t"; //tab between each element
cout << "n"; //new row
}
for(int i=0; i<rows; i++)
delete[] Matrix[i]; //free up the memory used
}
如果函数中数组的大小保持不变,可以考虑使用指针加第二个参数来表示数组的大小。
void function(int *array, const int size)
{
}
如果你想改变函数的大小,你可以考虑std::vector.
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值