function returning array

Hi All
i am trying to write the following function returning a array,but error saying "OutputArray" has unknown size. any advices?

1
2
3
4
5
6
double* MyFunction(double InputArray[],int length){
        double OutputArray[length];
        //some codes assigning values to OutputArray[0],[1],[2].....
         //
        return OutputArray;
}
I am also new in C++ but I think you could try:
 
double * OutputArray = new double[length];

instead of:
 
double OutputArray[length];


And when you are finished with this array, you MUST delete it like this:
1
2
myarray = Myfunction(inputarray,5);
delete myarray;
You can't dynamically size an array.
double OutputArray[length];
In C++, you cannot create an array of variable size like this. length must be known at compile time.

There is another problem with your code as well; anything you create inside a function on the stack (which is anything you create that you didn't create using new) ceases to exist when the function ends. You are returning a pointer to an array that ceases to exist when the function ends. All that array will be recycled and the memory space used for something else.

OutputArray is begging to be a proper C++ vector.
@yasar11732

I think you're getting a little mixed up. For clarification, if you ever delete a pointer to an array, you need to do it like this:

 
delete [] ptr_array;


Otherwise you'll find yourself in memory-leak city.
Otherwise you'll find yourself in memory-leak city.


I knew that, but I forgot. As I said, I am new to all this :)
I knew that, but I forgot. As I said, I am new to all this :)


No worries, just testing you. ;-)
Topic archived. No new replies allowed.