Click here to Skip to main content
15,899,314 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++

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
XML
#pragma once
#include <math.h>

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


CPP File
C#
#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;
}
Posted
Updated 6-Apr-12 21:17pm
v2

1 solution

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!
C++
float* c_Test::mf_ReturnFloatArray(float arrIn[])
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.
 
Share this answer
 
Comments
Lasantha72 7-Apr-12 4:43am    
Thank you very much, this is working.

About array type:
I use stack because general accepted idea is "The stack is much more efficient than the heap", without think about memory allocation. (In my real application size of returning array is sometimes 1000000). Thank you again for pointing me something that I have not considered. Now I am reading more about it from,
http://en.wikipedia.org/wiki/Dangling_pointer
http://en.wikipedia.org/wiki/Stack_(data_structure)http://en.wikipedia.org/wiki/Heap_%28data_structure%29rg/wiki/Stack_(data_structure)

If you know any useful links please post those.
OriginalGriff 7-Apr-12 4:48am    
Stack based items are quicker to allocate than heap based - all the memory above the current stack pointer is available - which is why you must not return pointers to it. When you exit the function, the stack pointer is moved back to where it was when you entered, and the next function you call considers all memory above it to be its too! :laugh:
Sergey Alexandrovich Kryukov 8-Apr-12 1:07am    
Exactly. 5 for the answer.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900