2013-03-18 78 views
2

我有谁的边界由另一个变量(不是常数)定义的array通过具有可变边界2D阵列到功能

int max = 10; 
int array[max][max]; 

现在我有它使用array,但是我没有的功能关于如何将数组传递给函数的想法。我该怎么做呢?

所以为了使它更清楚,我该如何做这项工作(我想过使用类,但变量max是由用户输入定义的,所以我不能让该数组成为类的成员,因为max会必须是一个常数)

void function (int array[max][max]) 
{ 
} 

在此先感谢。

+1

'最大'必须是一个常数,因为它是。 – chris 2013-03-18 01:23:44

+0

C++,使用类似'std :: vector'的stl类型。在C++中,你不能定义可变长度的数组。 – 2013-03-18 01:25:28

+1

您是否问有没有办法在C++中通过VLA?答案是*是*。它被称为“使用'std :: vector <>'并通过引用传递它。” – WhozCraig 2013-03-18 01:25:47

回答

0
#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 
} 
+0

这应该可以帮助您创建它由用户定义的大小。然后取出数组/矩阵并通过数组传递给它void void'function(int * array)' – cinelli 2013-03-18 02:12:12

+0

谢谢!我想我现在明白了。 – user2180680 2013-03-18 02:39:37

0

如果数组大小在函数中保持不变,则可以考虑使用指针加上第二个参数作为数组大小。

void function(int *array, const int size) 
{ 
} 

如果你想改变函数的大小,你可能真的考虑std :: std :: std实现。