2017-06-08 82 views
1

我試圖找到一種方法,在多維數組下面多維數組賦值給一個特定的列(C)

每分配一個特定的列到一個特定的值,我所知道的如何手動分配和通過for循環。

有沒有更簡單的方法去做呢?謝謝

#include <stdio.h> 
double Test1[4][5]; 
double a0, a1, a2, a3; 

int main() { 
    //Assigning one column in a specific row manually 
    Test1[1][1] = 1; 
    a0 = Test1[0][1]; 
    a1 = Test1[1][1]; 
    a2 = Test1[2][1]; 
    a3 = Test1[3][1]; 

    printf("a0 %f \r\n", a0); 
    printf("a1 %f \r\n", a1); 
    printf("a2 %f \r\n", a2); 
    printf("a3 %f \r\n", a3); 

    int row = sizeof(Test1)/sizeof(Test1[0]); 
    printf("rows %d \r\n", row); 
    int column = sizeof(Test1[0])/sizeof(Test1[0][0]); 
    printf("cols %d \r\n", column); 

    int L; 
    double a; 
    //Assigning one column in all rows to one 
    for (L = 0; L < row; L = L + 1) { 
    Test1[L][1] = 1; 
    } 

    a0 = Test1[0][1]; 
    a1 = Test1[1][1]; 
    a2 = Test1[2][1]; 
    a3 = Test1[3][1]; 

    printf("a0 %f \r\n", a0); 
    printf("a1 %f \r\n", a1); 
    printf("a2 %f \r\n", a2); 
    printf("a3 %f \r\n", a3); 

    return 0; 
} 
+1

封裝你環路成函數,恕我直言,您的反饋 – Garf365

+0

謝謝你的唯一途徑。 – LIO77

+1

你爲什麼要打印'\ r \ n'?只需使用'\ n',如果需要,轉換將自動完成。您的Windows將成爲'\ r \ r \ n' –

回答

0

沒有標準函數設置二維數組的列。在C中,多維數組有點幻想;他們編譯成一維數組。下面是一些代碼來證明值放鬆到一維數組:

#include <stdio.h> 

int main(){ 
    int test[10][2] = {0}; 
    //point to the 1st element 
    int * p1 = &test[0][0]; 

    //20th position is the 9th row, 2nd column 
    p1[19] = 5; 

    //9th element is the 5th row, 1st column 
    int * p2 = p1 + 8; 
    *p2 = 4; 

    printf("Value set to 5: %d\n",test[9][1]); 
    printf("Value set to 4: %d\n",test[4][0]); 
}