从函数返回数组
#include <iostream>
#include <ctime>
using namespace std;
int *getRandom();
int main(){
int *p = NULL;
p = getRandom();
// c++不支持函数外返回局部变量的地址,除非为static变量
for (int i = 0; i < 10; ++i) {
cout<<p+i<<"----"<<"*p = "<<*(p+i)<<endl;
}
return 0;
}
int *getRandom(){
static int r[10] = {0};
srand((unsigned )time(NULL));
for (int i= 0; i <10 ; ++i) {
r[i] = i;
}
return r;
}
- 让函数返回指针的方式返回,毕竟数组名就是首地址,数组就是指针,可以让函数返回指针的方式来实现返回数组。但是要知道数组元素个数,防止越界。
#include <iostream>
using namespace std;
void Matrix(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, 2, 1.23 };
float B[4] = {1, 1, 0, 0};
// 声明数组
float *M = new float[4];
Matrix(M, A, B);
cout << M[0] << " " << M[1] << endl;
cout << M[2] << " " << M[3] << endl;
// 删除数组
delete[] M;
return 0;
}