怎样让函数返回数组

这个问题属于非常初级的问题，但是对于初学不知道的人可能会比较头疼。C++中函数是不能直接返回一个数组的，但是数组其实就是指针，所以可以让函数返回指针来实现。比如一个矩阵相乘的函数，很容易地我们就写成：

 1 #include <iostream> 2  3 using namespace std; 4  5 float* MultMatrix(float A[4], float B[4]) 6 { 7     float M[4]; 8     M[0] = A[0]*B[0] + A[1]*B[2]; 9     M[1] = A[0]*B[1] + A[1]*B[3];10     M[2] = A[2]*B[0] + A[3]*B[2];11     M[3] = A[2]*B[1] + A[3]*B[3];12 13     return M;14 }15 16 int main()17 {18     float A[4] = { 1.75, 0.66, 0, 1.75 };19     float B[4] = {1, 1, 0, 0};20     float *M = MultMatrix(A, B);21     cout << M[0] << " " << M[1] << endl;22     cout << M[2] << " " << M[3] << endl;23 24     return 0;25 }

6.51468e-039 3.76489e-039

1.75 1.75
0 0
1.75 1.75
1.96875 1.75

7 　　 float M[4];

7　　float *M = new float[4];

1.75 1.75
0 0
1.75 1.75
0 0

20 　　 float *M = MultMatrix(A, B);

 1 #include <iostream> 2  3 using namespace std; 4  5 float* MultMatrix(float A[4], float B[4]) 6 { 7     float *M = new float[4]; 8     M[0] = A[0]*B[0] + A[1]*B[2]; 9     M[1] = A[0]*B[1] + A[1]*B[3];10     M[2] = A[2]*B[0] + A[3]*B[2];11     M[3] = A[2]*B[1] + A[3]*B[3];12     cout << M[0] << " " << M[1] << endl;13     cout << M[2] << " " << M[3] << endl;14 15     return M;16 }17 18 int main()19 {20     float A[4] = { 1.75, 0.66, 0, 1.75 };21     float B[4] = {1, 1, 0, 0};22     float *M = MultMatrix(A, B);23     cout << M[0] << " " << M[1] << endl;24     cout << M[2] << " " << M[3] << endl;25     delete[] M;26 27     return 0;28 }

1.75 1.75
0 0
1.75 1.75
0 0

 1 #include <iostream> 2  3 using namespace std; 4  5 void MultMatrix(float M[4], float A[4], float B[4]) 6 { 7     M[0] = A[0]*B[0] + A[1]*B[2]; 8     M[1] = A[0]*B[1] + A[1]*B[3]; 9     M[2] = A[2]*B[0] + A[3]*B[2];10     M[3] = A[2]*B[1] + A[3]*B[3];11 12     cout << M[0] << " " << M[1] << endl;13     cout << M[2] << " " << M[3] << endl;14 }15 16 int main()17 {18     float A[4] = { 1.75, 0.66, 0, 1.75 };19     float B[4] = {1, 1, 0, 0};20 21     float *M = new float[4];22     MultMatrix(M, A, B);23 24     cout << M[0] << " " << M[1] << endl;25     cout << M[2] << " " << M[3] << endl;26     delete[] M;27 28     return 0;29 }

posted @ 2011-09-18 22:57  杨溪  阅读(88290)  评论(25编辑  收藏  举报