next up previous contents
Next: 傳送一維陣列至函式 Up: 陣列 Previous: 字串   Contents

多維陣列

  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. 二維陣列初始化
    int a[3][4] = {  
     {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
     {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
     {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
    };
    
  5. 範例
    #include <stdio.h>
     
    int main ()
    {
       /* an array with 5 rows and 2 columns*/
       int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
       int i, j;
     
       /* output each array element's value */
       for ( i = 0; i < 5; i++ )
       {
          for ( j = 0; j < 2; j++ )
          {
             printf("a[%d][%d] = %d\n", i,j, a[i][j] );
          }
       }
       return 0;
    }
    



2015-01-16