2014-05-08 39 views
1

我有一個2D數組,我需要一次處理一列。我寫了一個示例代碼來說明我想要做什麼。它顯然不會編譯。使用矩陣作爲一維數組參數

float a[3][16]; // Create 2D array 

void function1() // This function will be called from my application 
{ 
    for (int i=0; i<16; i++) // For each column of the 2D array "a" 
    { 
     // Call this function that only take 1D array parameters 
     function2(a[][i]); // What I want is all rows in column i 
          // MATLAB syntax is: function2(a(:,i)); 
    } 
} 

void function2(float b[]) 
{ 
    // Something 
} 

我知道我可以創建一個臨時數組,將每個列保存到該列中,並將其用作function2中的參數。我想知道是否有更好的方法或如何做到這一點?

+0

Algol68的已陣列切片:-),比照http://en.wikipedia.org/wiki/Array_slicing#1968:_Algol_68。但是這意味着C沒有的多維數組的存在。 –

回答

4

最好的方法是將整個2d數組傳遞給function2()以及選擇列的參數。然後,只需沿軸進行迭代。

for (int i=0; i<16; i++) // For each column of the 2D array "a" 
{ 
    function2(a , i); 
} 

void function2(float b[Y][X] , size_t col) 
{ 
    for(size_t i = 0 ; i < Y ; i++) 
     b[i][col] = ... 
}