2012-07-25 81 views
4

我一直在试图传递一个未知大小的多维数组,给一个函数,到目前为止有没有运气,数组声明时,它的尺寸是变量:将多维数组传递给函数(C++)?

double a[b][b]; 

据正如我所知道的,当我声明函数时,我需要给出b的值,a可能是未知的。我试图将b声明为全局变量,但它表示它必须是常量。

即:

int b; 

double myfunction(array[][b]) 
{ 
} 

int main() 
{ 
int a; 
double c; 
double myarray[a][b]; 

c=myfunction(myarray); 

return 0; 
} 

有没有办法得到这个工作?

+1

不是很漂亮,但你不只是传入第一个元素的指针? – Chris 2012-07-25 17:33:09

+2

'std :: vector'让生活变得如此简单。 – chris 2012-07-25 17:34:02

+3

如果尺寸是可变的,则使用'std :: vector'或'boost :: multiarray'。 – 2012-07-25 17:34:15

回答

-1
void procedure (int myarray[][3][4]) 

更多关于此here

+2

我认为这是一个3维数组而不是2,否则你已经找到了一种我从未见过的语法[这当然是可能的! :)] – 2012-07-25 17:40:36

+1

看到Griwes对其他答案的评论。更好的链接将是[这个问题](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c)。 – chris 2012-07-25 17:51:51

4

传值:

double myfunction(double (*array)[b]) // you still need to tell b 

路过参考:

double myfunction(int (&myarray)[a][b]); // you still need to tell a and b 

模板方式:

template<int a, int b> double myfunction(int (&myarray)[a][b]); // auto deduction 
1

,如果你想通过未知大小的数组,你可以在堆声明数组这样

//Create your pointer 
int **p; 
//Assign first dimension 
p = new int*[N]; 
//Assign second dimension 
for(int i = 0; i < N; i++) 
p[i] = new int[M]; 


than you can declare a function like that: 
double myFunc (**array);