函数返回数组

来源:互联网 发布:大数据时代的喜与忧 编辑:程序博客网 时间:2024/06/05 21:13

函数是不能返回数组的,因此很直接的就想到的是返回指针,指针的声明位置也要注意,防止在子函数中内存释放掉了,因此用NEW进行动态分配内存,最后注意内存的释放(数组的释放与动态分配的变量的释放方式还有所不同)
错误的代码如下:

#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;}

正确的方式如下:

#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;}

更好的如下:,在子函数中不应该在进行动态声明指针,直接在主函数中声明之后传递进去就行了

#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;}
0 0
原创粉丝点击