How to Make a Function Return an Array in C++
Category Programming Techniques
This question is very basic, but it can be quite troublesome for beginners who don't know. In C++, a function cannot directly return an array, but an array is essentially a pointer, so you can let the function return a pointer to achieve this. For example, a matrix multiplication function can be easily written as follows:
Example
#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;
}
However, after running, the result is:
1.75 1.75
6.51468e-039 3.76489e-039
This is not the desired result. So we also added display code in the function to see if it's a calculation problem, and the result is:
1.75 1.75
0 0
1.75 1.75
1.96875 1.75
The calculation result is correct, but it changes after returning, and it's different from the last result. Why is that?
This is because the array M defined in the function is released by the system after the function execution is completed, so the result obtained in the calling function is naturally not the result after the calculation. One solution is to dynamically allocate memory and new an array in the function, so it won't be released.
So it should be changed from:
float M[4];
to:
float *M = new float[4];
After modifying and running, the result is:
1.75 1.75
0 0
1.75 1.75
0 0
Correct. But we haven't freed the space we applied for, and if we free it inside the function, the result will be the same as it was at the beginning.
Look at our calling code:
float *M = MultMatrix(A, B);
This actually points the M pointer to the first address of the M array in the function, and we can release the M pointer, which is the same as releasing the applied M array, because they point to the same memory space. So the code is modified to:
Example
#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;
}
The result of running is:
``` 1.75 1.75 0