next up previous contents
Next: 多維陣列 Up: 陣列 Previous: 陣列   Contents   DYWANG_HOME

一維陣列

  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};
    
  5. 初始化:較好的做法,中括號中不指定個數。
    double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
    
  6. 陣列在記憶體的存儲狀況。
    \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}

  7. 範例
    [dywang@dyw219 zzz]$ vim array1.c 
    [dywang@dyw219 zzz]$ cat array1.c
    #include <stdio.h>
    
    main() {
    	int i, x, a[7];
    
    	printf("Enter an integer: ");
    	scanf("%d", &x);
    	for ( i=0; i<7; i++) {
    		a[i] = i + x; 
    		printf("a[%d] = %d\n", i, a[i]);
    	}
    }
    
  8. 編譯
    [dywang@dyw219 zzz]$ gcc -o array1 array1.c
    
  9. 執行結果
    [dywang@dyw219 zzz]$ ./array1 
    Enter an integer: 5
    a[0] = 5
    a[1] = 6
    a[2] = 7
    a[3] = 8
    a[4] = 9
    a[5] = 10
    a[6] = 11
    



2020-01-02