2017-06-08 8 views
1

内の特定の列に値を代入それを手動で、forループを通して割り当てる方法。私は多次元配列に特定の値に特定の列を割り当てるための方法を見つけようとしている以下の</p> <p>パー、私の知る多次元配列(C)

これを行う簡単な方法はありますか?ありがとう

#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

おかげであなたのフィードバックのための唯一の方法である:ここでは値が1次元配列にくつろぐことを実証するためにいくつかのコードがあります。 – LIO77

+1

なぜ '\ r \ n'を印刷しますか? '\ n'を使うだけで、必要に応じて自動的に変換が行われます。あなたはWindows上で '\ r \ r \ n'になります –

答えて

0

2D配列の列を設定する標準機能はありません。 Cでは、多次元配列はちょっとした錯覚です。それらは1D配列にコンパイルされます。

#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]); 
} 
関連する問題