2014-12-04 84 views
1

我想爲我的論文開發一個代碼,並且我正試圖學習如何將二維數組傳遞給一個函數。我寫了一些東西。代碼在下面,它不是以這種形式工作的。我有這個錯誤:C++ 2d數組傳遞到一個函數

 
error: cannot convert ‘float (*)[(((sizetype)(((ssizetype)n) + -1)) + 1)]’ to ‘float (*)[2]’ for argument ‘3’ to ‘void func(int, int, float (*)[2], float)’ 
    func(m, n, a, omega); 

當我改變這個矩陣的聲明float a [m] [n];浮動[2] [2]它正在工作。先謝謝你。

void func(int m1, int n1, float a1[2][2], float omeg); 

using namespace std; 

int main(){ 

    int m = 2; 
    int n = 2; 
    int i, j; 
    float a[m][n]; 
    float x,y,z,omega, c; 
    x=0.1; 
    y=0.2; 
    z=0.3; 
    c = 0; 
    omega = (x*y*z)/x; 

    for(j = 0; j < n; j++) 
    { 
     for(i = 0; i < m; i++) 
     { 
     a[i][j] = 0.0; 
     } 
    } 
    func(m, n, a, omega); 

    cout << a[1][0] << endl; 

return 0; 
} 

void func(int m1, int n1, float a1[][2], float omeg) 
{ 
    for(int j = 0; j < n1; j++) 
     { 
      for(int i = 0; i < m1; i++) 
      { 
      a1[i][j] = omeg * 5; 
      } 
     } 

} 
+1

使用'const'爲'M'和'N',否則您使用非標準擴展可變長度陣列(VLA)。 – Jarod42 2014-12-04 14:42:58

+0

爲什麼不使用vector(www.cplusplus.com/reference/vector/vector/)而不是數組? – geoalgo 2014-12-04 14:44:21

+0

我甚至沒有嘗試發佈答案,你正在嘗試使用C++ w/o有關指針和參數傳遞的任何知識。你需要在編寫代碼之前學習這些。 – 2014-12-04 14:48:28

回答

0

使用constmn,否則你使用非標準擴展可變長度數組(VLA)。

我建議使用更直觀的std::array(如果尺寸是動態的,則爲std::vector)。

0

我的理解是,該聲明

float a[m][n] 

是不可能的。以這種方式指定變量或常量數組的大小是不可能的。被宣佈爲

float a[2][2] 

是更好看,如果大小實際上2是2,但內部是一樣的,如果申報

float (*a)[2] 

使用。對於C數組,在定義數組和聲明一個固定大小的數組之後不可能知道大小,因爲參數是不可能的,至少不會產生所需的效果。

+0

這是不對的 - float a [2] [2]'作爲參數類型相當於float(* a)[2]',而不是'float ** a'。因此,您只能省略第一維尺寸:'float a [] [2]'。 – 2014-12-04 14:49:07

+0

我錯了,並糾正了我的答案;但結果究竟是什麼?據我的理解,這仍然沒有強制檢查邊界或提供任何其他信息,以防止不良使用,是否正確? – Codor 2014-12-04 14:52:32

0

試試這個: -

int main(){ 

    int i, j; 
    float a[2][2]; 
    float x,y,z,omega, c; 
    x=0.1; 
    y=0.2; 
    z=0.3; 
    c = 0; 
    omega = (x*y*z)/x; 

    for(j = 0; j < 2; j++) 
    { 
     for(i = 0; i < 2; i++) 
     { 
      a[i][j] = 0.0; 
     } 
    } 
    func(a, omega); 

    cout << a[1][0] << endl; 

    return 0; 
    } 

    void func(float a1[2][2], float omeg) 
    { 
    for(int j = 0; j < 2; j++) 
    { 
     for(int i = 0; i < 2; i++) 
     { 
     a1[i][j] = omeg * 5; 
     } 
    } 
    }