C++ 不允许返回一个完整的数组作为函数的参数。但是,您可以通过指定不带索引的数组名来返回一个指向数组的指针。
如果您想要从函数返回一个一维数组,您必须声明一个返回指针的函数,如下:
int myFunction(){. . .}
另外,C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为 *static
变量。
现在,让我们来看下面的函数,它会生成 10 个随机数,并使用数组来返回它们,具体如下:

实例

  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. using namespace std;
  5. // 要生成和返回随机数的函数
  6. int * getRandom( )
  7. {
  8. static int r[10]; //函数在定义前并不存在,所以必须定义为静态才能正确返回指针
  9. // 设置种子
  10. srand( (unsigned)time( NULL ) );
  11. for (int i = 0; i < 10; ++i)
  12. {
  13. r[i] = rand();
  14. cout << r[i] << endl;
  15. }
  16. return r;
  17. }
  18. // 要调用上面定义函数的主函数
  19. int main ()
  20. {
  21. // 一个指向整数的指针
  22. int *p;
  23. p = getRandom();
  24. for ( int i = 0; i < 10; i++ )
  25. {
  26. cout << "*(p + " << i << ") : ";
  27. cout << *(p + i) << endl;
  28. }
  29. return 0;
  30. }

C++中函数是不能直接返回一个数组的,但是数组其实就是指针,所以可以让函数返回指针来实现:

  1. #include <iostream>
  2. using namespace std;
  3. void MultMatrix(float M[4], float A[4], float B[4])
  4. {
  5. M[0] = A[0]*B[0] + A[1]*B[2];
  6. M[1] = A[0]*B[1] + A[1]*B[3];
  7. M[2] = A[2]*B[0] + A[3]*B[2];
  8. M[3] = A[2]*B[1] + A[3]*B[3];
  9. cout << M[0] << " " << M[1] << endl;
  10. cout << M[2] << " " << M[3] << endl;
  11. }
  12. int main()
  13. {
  14. float A[4] = { 1.75, 0.66, 0, 1.75 };
  15. float B[4] = {1, 1, 0, 0};
  16. float *M = new float[4];
  17. MultMatrix(M, A, B);
  18. cout << M[0] << " " << M[1] << endl;
  19. cout << M[2] << " " << M[3] << endl;
  20. delete[] M; //分解指针,释放空间
  21. return 0;
  22. }