无法从VC ++ 2008函数返回浮点数组-错误C2440 [英] Cannot return float array from VC++ 2008 function - error C2440

查看:86
本文介绍了无法从VC ++ 2008函数返回浮点数组-错误C2440的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我尝试使用VC ++(VS 2008)函数返回一个浮点数组.但是它给出了以下错误
"c_Test.cpp(17):错误C2440:"返回:无法从" float [4]转换为" float"

第17行是返回OP;"完整的代码如下所示.如果有人能帮助我解决问题,我将不胜感激(我是VC ++的新手,但可以使用VB).提前谢谢.


头文件

I tried to return a float array using VC++ (VS 2008) function. But it gives following error
"c_Test.cpp(17) : error C2440: ''return'' : cannot convert from ''float [4]'' to ''float'' "

Line 17 is "return OP;" and complete code is shown below. I would be thankful if someone give me a help to solve the problem (I am new to VC++, but OK with VB). Thanks in advance.


Header File

#pragma once
#include <math.h>

class c_Test
{
float mf_ReturnFloatArray(float arrIn[]);
};



CPP文件



CPP File

#include "StdAfx.h"
#include "c_Test.h"

float c_Test::mf_ReturnFloatArray(float arrIn[])
{

    const int N= sizeof(arrIn);
    float a;
    float OP[N];

    for (int m = 0; m <= N-1; m++)
        {
            a=m/2;
            OP[m] = sqrt(a);
        }

return OP;
}

推荐答案

这有一些问题.
如果要返回浮点数组,那么将函数声明为返回浮点数是错误的方法!
There are a few things wrong with that.
If you want to return a float array, then declaring the function as returning a float is the wrong way to go!
float* c_Test::mf_ReturnFloatArray(float arrIn[])

会是一个更好的主意.

其次,返回一个已经在堆栈上创建的数组不是一个好主意-它被称为hanging referencedangling reference,因为它返回指向内存的指针,该指针将由下一个函数重复使用称呼.要返回数组,应在堆上创建它,并在完成后正确释放内存.
否则,您会遇到间歇性故障,这是可以跟踪和解决的PITA.

Would be a better idea.

Secondly, it is not a good idea to return an array that has been created on the stack anyway - it is called a hanging reference or a dangling reference because it returns a pointer to memory that will be re-used by the next function call. To return an array, you should create it on the heap and release the memory correctly when you have finished with it.
Other wise, you will get intermittent faults, which are a PITA to track down and solve.


这篇关于无法从VC ++ 2008函数返回浮点数组-错误C2440的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆