C++ 从函数返回数组
C++ 教程
· 2019-02-25 18:44:48
C++ 不允许返回一个完整的数组作为函数的参数。但是,您可以通过指定不带索引的数组名来返回一个指向数组的指针。
如果您想要从函数返回一个一维数组,您必须声明一个返回指针的函数,如下:
int * myFunction()
{
.
.
.
}
另外,C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为 static 变量。
现在,让我们来看下面的函数,它会生成 10 个随机数,并使用数组来返回它们,具体如下:
实例
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// 要生成和返回随机数的函数
int * getRandom( )
{
static int r[10];
// 设置种子
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 10; ++i)
{
r[i] = rand();
cout << r[i] << endl;
}
return r;
}
// 要调用上面定义函数的主函数
int main ()
{
// 一个指向整数的指针
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ )
{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
624723190 1468735695 807113585 976495677 613357504 1377296355 1530315259 1778906708 1820354158 667126415 *(p + 0) : 624723190 *(p + 1) : 1468735695 *(p + 2) : 807113585 *(p + 3) : 976495677 *(p + 4) : 613357504 *(p + 5) : 1377296355 *(p + 6) : 1530315259 *(p + 7) : 1778906708 *(p + 8) : 1820354158 *(p + 9) : 667126415
点击查看所有 C++ 教程 文章: https://www.codercto.com/courses/l/18.html
Google's PageRank and Beyond
Amy N. Langville、Carl D. Meyer / Princeton University Press / 2006-7-23 / USD 57.50
Why doesn't your home page appear on the first page of search results, even when you query your own name? How do other web pages always appear at the top? What creates these powerful rankings? And how......一起来看看 《Google's PageRank and Beyond》 这本书的介绍吧!