函数返回数组

函数是不能返回数组的,因此很直接的就想到的是返回指针,指针的声明位置也要注意,防止在子函数中内存释放掉了,因此用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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值