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;}
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;}
