小白教程
所有教程
关于
Search
172.70.178.200
172.70.178.200
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“C return pointer from functions”的源代码
本页内容
上一节:
C_passing_pointers_to_functions
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:从函数返回指针}}[[Category:c pointers|5]] = C 从函数返回指针 = [[c pointers|C 指针]] 在上一章中,我们已经了解了 C 语言中如何从函数返回数组,类似地,C 允许您从函数返回指针。为了做到这点,您必须声明一个返回指针的函数,如下所示: <pre> int * myFunction() { . . . } </pre> 另外,C 语言不支持在调用函数时返回局部变量的地址,除非定义局部变量为 '''static''' 变量。 现在,让我们来看下面的函数,它会生成 10 个随机数,并使用表示指针的数组名(即第一个数组元素的地址)来返回它们,具体如下: <sample title="" desc="" lang="c" hererun="1"> #include <stdio.h> #include <time.h> #include <stdlib.h> /* 要生成和返回随机数的函数 */ int * getRandom( ) { static int r[10]; int i; /* 设置种子 */ srand( (unsigned)time( NULL ) ); for ( i = 0; i < 10; ++i) { r[i] = rand(); printf("%d\n", r[i] ); } return r; } /* 要调用上面定义函数的主函数 */ int main () { /* 一个指向整数的指针 */ int *p; int i; p = getRandom(); for ( i = 0; i < 10; i++ ) { printf("*(p + [%d]) : %d\n", i, *(p + i) ); } return 0; } </sample> 当上面的代码被编译和执行时,它会产生下列结果: <pre> 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 </pre> [[c pointers|C 指针]]
返回至“
C return pointer from functions
”。
上一节:
C_passing_pointers_to_functions