next up previous contents
Next: 雙重指標 Up: 指標 Previous: 指標比較   Contents   DYWANG_HOME

指標陣列

  1. 指標變數跟其他型態的變數一樣,可以宣告成「指標陣列」。
    int *ptr[MAX];
    
  2. 範例一:整數指標
    [dywang@dyw219 zzz]$ vim pointer5.c
    [dywang@dyw219 zzz]$ cat pointer5.c
    #include <stdio.h>
    
    main () {
    	int var[]={11, 22, 33, 44};
    	int MAX=sizeof(var)/sizeof(int);
    	int i, *ptr[MAX];
    
    	for ( i=0; i<MAX; i++) {
    		ptr[i] = &var[i];
    		printf( "*ptr[%d]=%d\t\tptr[%d]=%x\n", i, *ptr[i], i, ptr[i]);
    	}
    }
    
  3. 編譯
    [dywang@dyw219 zzz]$ gcc -o pointer5 pointer5.c
    
  4. 執行結果
    [dywang@dyw219 zzz]$ ./pointer5
    *ptr[0]=11		ptr[0]=8d1ef780
    *ptr[1]=22		ptr[1]=8d1ef784
    *ptr[2]=33		ptr[2]=8d1ef788
    *ptr[3]=44		ptr[3]=8d1ef78c
    
  5. 範例二:字元指標
    [dywang@dyw219 zzz]$ vim pointer6.c
    [dywang@dyw219 zzz]$ cat pointer6.c
    #include <stdio.h>
    
    main () {
    	char *name[]={ "dywang", "linda", "peter", "rita" };
    	int MAX=sizeof(name)/sizeof(*name);
    	int i;
    
    	for ( i=0; i<MAX; i++)
    		printf( "name[%d]=%s\n", i, name[i]);
    }
    
  6. 編譯
    [dywang@dyw219 zzz]$ gcc -o pointer6 pointer6.c
    
  7. 執行結果
    [dywang@dyw219 zzz]$ ./pointer6
    name[0]=dywang
    name[1]=linda
    name[2]=peter
    name[3]=rita
    



De-Yu Wang 2021-01-11