next up previous contents
Next: 字元陣列-字串 Up: 陣列 Previous: 一維陣列   Contents   DYWANG_HOME

多維陣列

  1. 多維陣列宣告
    type name[size1][size2]...[sizeN];
    
  2. 二維陣列宣告
    type arrayName [ x ][ y ];
    
  3. 3x5 二維陣列
    \begin{tikzpicture}[node distance=5em,auto]\setlength \baselineskip{1ex}
\node [input](input0) {};
\node [block,text width=4.5em,below of=input0] (n0) {a[0][0]};
\node [block,text width=4.5em,right of=n0] (n1) {a[0][1]};
\node [block,text width=4.5em,right of=n1] (n2) {a[0][2]};
\node [block,text width=4.5em,right of=n2] (n3) {a[0][3]};
\node [block,text width=4.5em,right of=n3] (n4) {a[0][4]};
\node [block,text width=4.5em,below of=n0,node distance=2em] (n10) {a[1][0]};
\node [block,text width=4.5em,right of=n10] (n11) {a[1][1]};
\node [block,text width=4.5em,right of=n11] (n12) {a[1][2]};
\node [block,text width=4.5em,right of=n12] (n13) {a[1][3]};
\node [block,text width=4.5em,right of=n13] (n14) {a[1][4]};
\node [block,text width=4.5em,below of=n10,node distance=2em] (n20) {a[2][0]};
\node [block,text width=4.5em,right of=n20] (n21) {a[2][1]};
\node [block,text width=4.5em,right of=n21] (n22) {a[2][2]};
\node [block,text width=4.5em,right of=n22] (n23) {a[2][3]};
\node [block,text width=4.5em,right of=n23] (n24) {a[2][4]};
\node [above of=n0,node distance=2em](e0) {Column 0};
\node [above of=n1,node distance=2em](e1) {Column 1};
\node [above of=n2,node distance=2em](e2) {Column 2};
\node [above of=n3,node distance=2em](e3) {Column 3};
\node [above of=n4,node distance=2em](e4) {Column 4};
\node [left of=n0,node distance=5em](row0) {Row 0};
\node [left of=n10,node distance=5em](row1) {Row 1};
\node [left of=n20,node distance=5em](row2) {Row 2};
\end{tikzpicture}

  4. 3x4 二維陣列初始化, 3 可由初始化得知,所以可以省略,但 4 不能省略,若省略則陣列 3x4 及 4x3 會混淆。
    int a[3][4]={{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
    
  5. 範例
    [dywang@dyw219 zzz]$ vim array2.c
    [dywang@dyw219 zzz]$ cat array2.c
    #include <stdio.h>
    
    main() {
    	int a[][4]={{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
    	int i, j;
    
    	for ( i=0; i<3; i++ ) {
    		for ( j=0; j<4; j++ ) {
    			printf("a[%d][%d] = %d\n", i,j, a[i][j] );
    		}
    	}
    }
    
  6. 編譯
    [dywang@dyw219 zzz]$ gcc -o array2 array2.c
    
  7. 執行結果
    [dywang@dyw219 zzz]$ ./array2
    a[0][0] = 0
    a[0][1] = 1
    a[0][2] = 2
    a[0][3] = 3
    a[1][0] = 4
    a[1][1] = 5
    a[1][2] = 6
    a[1][3] = 7
    a[2][0] = 8
    a[2][1] = 9
    a[2][2] = 10
    a[2][3] = 11
    



De-Yu Wang 2021-01-11