数组在函数中做形参声明时可以有两种形式①数组②指针,举例如下:
void sum(int arr[],int len)
{
//函数体
}
void sum(int *arr,int len)
{
//函数体
}
当且仅当用于函数头或函数原型中,int *arr和int arr[]的含义才是相同的,他们都意味着arr是一个int指针。然而,数组表示法(int arr[])提醒用户,arr不仅指向int,还指向int数组的第一个元素。 怎样让函数返回数组,这个问题属于非常初级的问题,但是对于初学不知道的人可能会比较头疼。C++中函数是不能直接返回一个数组的,但是数组其实就是指针,所以可以让函数返回指针来实现。比如一个矩阵相乘的函数,很容易地我们就写成:
#include <iostream>
using namespace std;
float* MultMatrix(float A[4], float B[4])
{
float M[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];
return M;
}
int main()
{
float A[4] = { 1.75, 0.66, 0, 1.75 };
float B[4] = {1, 1, 0, 0};
float *M = MultMatrix(A, B);
cout << M[0] << " " << M[1] << endl;
cout << M[2] << " " << M[3] << endl;
return 0;
}
但是运行后发现结果是:1.75 1.75
6.51468e-039 3.76489e-039
根本不是想要的结果,此时我们在调用的函数内设置断点进行调试, 发现计算的结果是正确的,但返回后就变了,而且跟上次的结果不一样。这是为什么呢?
因为在函数中定义的数组M在函数执行完后已经被系统释放掉了,所以在调用函数中得到的结果当然不是计算后的结果。有一个解决办法就是动态分配内存,在函数中new一个数组,这样就不会被释放掉了。
#include <iostream>
using namespace std;
float* MultMatrix(float A[4], float B[4])
{
float *M = new float[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;
return M;
}
int main()
{
float A[4] = { 1.75, 0.66, 0, 1.75 };
float B[4] = {1, 1, 0, 0};
float *M = MultMatrix(A, B);
cout << M[0] << " " << M[1] << endl;
cout << M[2] << " " << M[3] << endl;
delete[] M;
return 0;
}
运行结果:
1.75 1.75
0 0
1.75 1.75
0 0
没有问题,new的空间也delete掉了。
#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;
}