2014-04-01 121 views
0

我看了關於這一問題的其他職位,但不能似乎真的將它應用到我的情況特別這篇文章:Passing a 2D array to a C++ function2維數組

int compute(int size, int graph[][size], int u, int v) 

,並出現以下錯誤:

candidate function not viable: no known conversion from 
    'int [size][size]' to 'int (*)[size]' for 2nd argument 
int compute(int size, int graph[][size], int u, int v) 

當我打電話,我的主要方法,這個功能我做了以下的方法:

compute(size,matrix,0,size-1) 

的我的問題是什麼?

+0

嘗試定義'INT計算(INT大小,INT圖[] [],INT U,int v)按' – jsantander

+0

什麼是你的代碼中的 '矩陣' 的定義是什麼? – Ryand

+0

'matrix'都將被聲明爲'INT *矩陣大小]'而不是'INT矩陣[大小] [SIZE]'或者你必須改變你的函數的定義jsantander說。 – user3018144

回答

1
template<size_t sizex, size_t sizey> 
int compute(int (&graph)[sizex][sizey], int u, int v); 

這種行爲的人所期望的方式,例如sizeof而無需擔心棘手的指針轉換返回正確的大小。它也只會讓你通過2D數組,而不是指針。

+0

但是,只有當sizex和sizey是'constexpr'時纔會起作用嗎? – Bathsheba

+0

@Bathsheba在某種程度上,是的。到目前爲止,在C++中不可能擁有可變長度數組,因此不可能將沒有固定編譯時間大小的數組傳遞給此函數。如果VLA得到支持,這可能會中斷。從C++ 14開始,這將適用於任何2D陣列。 – nwp

+0

因此,考慮自己在C++ 14到期時獲得遠期合約,立即解決。 – Bathsheba

1

以下爲我工作對於g ++

const int SIZE=3; 
int compute(int s, int graph[][SIZE], int u, int v) { 
     return 0; 
} 


int main(int argc,char **argv) { 
    int matrix[SIZE][SIZE]; 
    compute(SIZE,matrix,0,SIZE-1); 
} 

注意SIZE是整數常數,是不與計算的第一參數相混淆。

+0

您可以根據用戶輸入更改大小的值嗎? – user3485137

+1

你可能想看看http://www.cplusplus.com/forum/articles/17108/ – jsantander