next up previous contents
Next: 傳送指標到函式 Up: 指標 Previous: 指標陣列   Contents   DYWANG_HOME

雙重指標

  1. 指標存放變數的位址,透過這個位址就可以存取該變數的內容。雙重指標 (pointer to pointer) 讓指標指到另一個「指標變數」,宣告:
       int  var;
       int  *ptr;
       int  **pptr;
    

    \begin{tikzpicture}[node distance=8em]\setlength \baselineskip{1ex}
\node [block,text width=5em] (adr0) {address of var pointer};
\node [block,text width=5em,right of=adr0] (adr1) {var address};
\node [block,text width=5em,right of=adr1] (value) {var value};
\node [above of=adr0,node distance=2em](ptr0) {**pptr};
\node [above of=adr1,node distance=2em](ptr1) {*ptr};
\node [above of=value,node distance=2em](var) {var};
\path [line] (adr0) -- (adr1);
\path [line] (adr1) -- (value);
\end{tikzpicture}

  2. 範例
    [dywang@dyw219 zzz]$ vim pointer7.c
    [dywang@dyw219 zzz]$ cat pointer7.c
    #include <stdio.h>
    
    main () {
    	int var=1234;
    	int *ptr;
    	int **pptr;
    
    	ptr = &var;
    	pptr= &ptr;
    
    	printf( "var=%d\n*ptr=%d\n**pptr=%d\n", var, *ptr, **pptr);
    }
    
  3. 編譯
    [dywang@dyw219 zzz]$ gcc -o pointer7 pointer7.c
    
  4. 執行結果
    [dywang@dyw219 zzz]$ ./pointer7
    var=1234
    *ptr=1234
    **pptr=1234
    



De-Yu Wang 2021-01-11