next up previous contents
Next: 陣列位址指標 Up: 陣列 Previous: 傳送一維陣列至函式   Contents

從函式回傳陣列

  1. C 語言無法讓函式回傳整個陣列值,但可以藉由回傳陣列的位址指標,達到回傳陣列的目的。
    int * myFunction()
    {
    ....
    }
    
  2. 範例
    #include <stdio.h>
    
    /* function to generate and return 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( "r[%d] = %d\n", i, 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