2013-02-19 19 views
0

我想有一個函數,它執行以下操作:C:以引用的函數傳遞二維數組和如何使用它們裏面

int doFunction(int* nIndex) 
{ 

    //nIndex is a 2-D array of any size. 
// I would like to fill this array inside this function. 
//Eg: in nIndex[2][3], i would like to put 5. 

} 

int result; 
int myIndex[5][6]; 

result = doFunction(myIndex); 

可能有人請幫助我的兩件事情: 1 。是以上語法正確的函數定義,需要任意大小的二維數組? 2.當我將myIndex傳入函數時,語法正確嗎? 3.如何填充函數中的數組,或者如何訪問其字段?

感謝。

+2

我敢肯定,這東西一式兩份。可能(http://stackoverflow.com/questions/404232/how-do-i-pass-a-reference-to-a-two-dimensional-array-to-a-function)(http://stackoverflow.com/questions/8659304/passing-two-dimensional-array-to-a-function-by-refrence-c-programming),(http://stackoverflow.com/questions/14548753/passing-a-multidimensional-variable-length數組功能)以及其他功能。 – phoeagon 2013-02-19 12:09:29

回答

0

宣言和定義:

// either void fill_arr(int arr[][5]) or: 
void fill_arr(int arr[3][5]) 
{ 
    int i j; 
    for (i = 0; i < 3; i++) { 
     for (j = 0; j < 5; j++) { 
      arr[i][j] = 42; 
     } 
    } 
} 

呼叫:

int arr[3][5]; 
fill_arr(arr); 
+0

這當然有用,但是你僅限於int [3] [5]或者最多int [] [5] ... – 2013-02-19 12:18:32

+0

謝謝,但是我希望兩個數組的大小都是可變的 – Sunny 2013-02-19 12:19:41

+0

@Sunny然後通過在另一個參數'len'中作爲內部訂閱的範圍。然後作爲'arr +(i * len)+ j'訪問'arr [i] [j]'。如果你討厭這樣做,請使用['boost :: multi_array'](http://www.boost.org/doc/libs/1_53_0/libs/multi_array/doc/user.html) – phoeagon 2013-02-19 12:22:45