小白教程
所有教程
关于
Search
172.69.6.74
172.69.6.74
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“C return arrays from function”的源代码
本页内容
上一节:
C_passing_arrays_to_functions
下一节:
C_pointer_to_an_array
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:从函数返回数组}}[[Category:c arrays|3]] = C 从函数返回数组 = [[c arrays|C 数组]] C 语言不允许返回一个完整的数组作为函数的参数。但是,您可以通过指定不带索引的数组名来返回一个指向数组的指针。我们将在下一章中讲解有关指针的知识,您可以先跳过本章,等了解了 C 指针的概念之后,再来学习本章的内容。 如果您想要从函数返回一个一维数组,您必须声明一个返回指针的函数,如下: <sample title="" desc="" lang="c" hererun="1"> int * myFunction() { . . . } </sample> 另外,C 不支持在函数外返回局部变量的地址,除非定义局部变量为 '''static''' 变量。 现在,让我们来看下面的函数,它会生成 10 个随机数,并使用数组来返回它们,具体如下: <sample title="" desc="" lang="c" hererun="1"> #include <stdio.h> #include <stdlib.h> #include <time.h> /* 要生成和返回随机数的函数 */ int * getRandom( ) { static int r[10]; int i; /* 设置种子 */ srand( (unsigned)time( NULL ) ); for ( i = 0; i < 10; ++i) { r[i] = rand(); printf( "r[%d] = %d\n", i, 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> r[0] = 313959809 r[1] = 1759055877 r[2] = 1113101911 r[3] = 2133832223 r[4] = 2073354073 r[5] = 167288147 r[6] = 1827471542 r[7] = 834791014 r[8] = 1901409888 r[9] = 1990469526 *(p + 0) : 313959809 *(p + 1) : 1759055877 *(p + 2) : 1113101911 *(p + 3) : 2133832223 *(p + 4) : 2073354073 *(p + 5) : 167288147 *(p + 6) : 1827471542 *(p + 7) : 834791014 *(p + 8) : 1901409888 *(p + 9) : 1990469526 </pre> [[c arrays|C 数组]]
返回至“
C return arrays from function
”。
上一节:
C_passing_arrays_to_functions
下一节:
C_pointer_to_an_array