将具有可变边界的2d数组传递给函数

passing 2d array with variable boundaries to a function

本文关键字:数组 函数 2d 边界      更新时间:2023-10-16

我有一个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.