next up previous contents
Next: Structures 和 Unions Up: 指標(pointers) Previous: 傳送指標到函式   Contents

從函式回傳指標

  1. 宣告
    int * myFunction()
    {
    ...
    }
    
  2. 範例:在函式中產中 10 個隨機數字,利用指標回傳數字陣列。
    #include <stdio.h>
    #include <time.h>
     
    /* function to generate and retrun random numbers. */
    int * getRandom( )
    {
       static int  r[10];
       int i;
     
       /* set the seed */
       srand( (unsigned)time( NULL ) );
       for ( i = 0; i < 10; ++i)
       {
          r[i] = rand();
          printf("%d\n", r[i] );
       }
     
       return r;
    }
     
    /* main function to call above defined function */
    int main ()
    {
       /* a pointer to an int */
       int *p;
       int i;
    
       p = getRandom();
       for ( i = 0; i < 10; i++ )
       {
           printf("*(p + [%d]) : %d\n", i, *(p + i) );
       }
     
       return 0;
    }
    


2015-01-16