2012-07-25 84 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);