next up previous contents
Next: 字串 Up: 陣列 Previous: 陣列   Contents

一維陣列

  1. 陣列存在於一段連續的記憶體,最小的記憶體存陣列第一個值,依此類推。

    \begin{tikzpicture}[node distance=6em]\setlength \baselineskip{1ex}
\node [input](input0) {};
\node [block,text width=6em, below of=input0,node distance=4em] (n0) {numbers[0]};
\node [block,text width=6em,right of=n0] (n1) {numbers[1]};
\node [block,text width=6em,right of=n1] (n2) {numbers[2]};
\node [block,text width=6em,right of=n2] (n3) {numbers[3]};
\node [block,text width=6em,right of=n3] (nn) {...};
\node [input,name=inputn,above of=nn,node distance=4em] {};
\node [above of=inputn,node distance=0.5em](le) {Last Element};
\path [line] node[above]{First Element}(input0) --(n0);
\path [line] (inputn) --(nn);
\end{tikzpicture}

  2. 宣告陣列
    type arrayName [ arraySize ];
    
  3. 範例
    double balance[10];
    
  4. 初始化
    double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
    /*%* 較好的做法,中括號中不指定個數 *)*/
    double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
    
  5. 陣列在記憶體的存儲狀況。

    \begin{tikzpicture}[node distance=5em,auto]\setlength \baselineskip{1ex}
\node [input](input0) {};
\node [block,text width=4.5em,below of=input0] (n0) {1000.0};
\node [left of=n0,node distance=5em](balance) {balance};
\node [block,text width=4.5em,right of=n0] (n1) {2.0};
\node [block,text width=4.5em,right of=n1] (n2) {3.4};
\node [block,text width=4.5em,right of=n2] (n3) {17.0};
\node [block,text width=4.5em,right of=n3] (n4) {50.0};
\node [above of=n0,node distance=2em](e0) {0};
\node [above of=n1,node distance=2em](e1) {1};
\node [above of=n2,node distance=2em](e2) {2};
\node [above of=n3,node distance=2em](e3) {3};
\node [above of=n4,node distance=2em](e4) {4};
\end{tikzpicture}

  6. 範例
    #include <stdio.h>
     
    int main ()
    {
       int n[ 10 ]; /* n is an array of 10 integers */
       int i,j;
     
       /* initialize elements of array n to 0 */         
       for ( i = 0; i < 10; i++ )
       {
          n[ i ] = i + 100; /* set element at location i to i + 100 */
       }
       
       /* output each array element's value */
       for (j = 0; j < 10; j++ )
       {
          printf("Element[%d] = %d\n", j, n[j] );
       }
     
       return 0;
    }
    



2015-01-16