目录

从C中的函数返回指针(Return pointer from functions in C)

我们在上一章中已经看到C编程如何允许从函数返回数组。 类似地,C还允许从函数返回指针。 为此,您必须声明一个返回指针的函数,如下例所示 -

int * myFunction() {
   .
   .
   .
}

要记住的第二点是,在函数外部返回局部变量的地址不是一个好主意,因此您必须将局部变量定义为static变量。

现在,考虑以下函数,它将生成10个随机数,并使用表示指针的数组名称返回它们,即第一个数组元素的地址。

#include <stdio.h>
#include <time.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("%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;
}

当上面的代码一起编译并执行时,它会产生以下结果 -

1523198053
1187214107
1108300978
430494959
1421301276
930971084
123250484
106932140
1604461820
149169022
*(p + [0]) : 1523198053
*(p + [1]) : 1187214107
*(p + [2]) : 1108300978
*(p + [3]) : 430494959
*(p + [4]) : 1421301276
*(p + [5]) : 930971084
*(p + [6]) : 123250484
*(p + [7]) : 106932140
*(p + [8]) : 1604461820
*(p + [9]) : 149169022
↑回到顶部↑
WIKI教程 @2018