C++ 从函数返回数组
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

文人墨客
srand以一个时间点为参数播种,当执行的随机数少的时候,时间没有变化,产生的随机数是一样的,下面这例子,输入的很多,前面几十个随机数都是一样的,当时间增加一个单位之后生成的随机数就不一样了,会递增,所以 srand 函数要放在 rand 循环的外面避免每次循环产生的随机数一样。
# include<stdlib.h> # include<iostream> # include<time.h> int main(){ // srand((unsigned)time(NULL)); for (int i = 0; i < 100000; ++i) { srand((unsigned)time(NULL)); int a=rand(); std::cout<<a<<std::endl; } }文人墨客
『返回指针的函数』和『指向函数的指针』非常相似,使用时特别注意区分。
返回指针的函数定义:char * upper(char *str)
指向函数的指针:char (*fun)(int int)
返回指针的函数:
char * upper(char *str) { char *dest = str; while(*str != NULL) { if(*str >= 'a' && *str <= 'z') { *str -= 'a' - 'A'; } str++; } return dest; }指向函数的指针:
int add(int a,int b) { return a+b; } int min() { int (*fun)() = add; int result = (*fun)(1,2); char hello[] = "Hello"; char *dest = upper(heLLo); }int result = (*fun)(1,2); 是指向 add 函数的函数,执行结果 result=3。
char *dest = upper(heLLo); 将 hello 字符串中的小写字母全部转换为大写字母。
文人墨客
C++中函数是不能直接返回一个数组的,但是数组其实就是指针,所以可以让函数返回指针来实现:
#include <iostream> using namespace std; void MultMatrix(float M[4], float A[4], float B[4]) { M[0] = A[0]*B[0] + A[1]*B[2]; M[1] = A[0]*B[1] + A[1]*B[3]; M[2] = A[2]*B[0] + A[3]*B[2]; M[3] = A[2]*B[1] + A[3]*B[3]; cout << M[0] << " " << M[1] << endl; cout << M[2] << " " << M[3] << endl; } int main() { float A[4] = { 1.75, 0.66, 0, 1.75 }; float B[4] = {1, 1, 0, 0}; float *M = new float[4]; MultMatrix(M, A, B); cout << M[0] << " " << M[1] << endl; cout << M[2] << " " << M[3] << endl; delete[] M; return 0; }