Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c/c++: error of printing a double array returned by a function

I got a problem with the following code:

#include <iostream>
using namespace std;

double* FillArray(void) 
{   
    double result[5]; 

    for (int i = 0; i<5;i++){
        result[i]=(double) i;

    }
    return result; // return the pointer
}

int main()
{   

    double * a = FillArray();
    for (int i = 0; i<5;i++){
        cout << a[i] << endl; // print out the array
    }

    return 0;
}

The outputs are strange:

0
3.47187e-236
8.89753e-308
8.8976e-308
3.90251e-236

Could you tell what wrong in my code? I tried to use a function to return an array, and print out it in the main().

like image 583
lxw Avatar asked May 07 '26 21:05

lxw


1 Answers

You are returning a pointer to a local variable, the array result. This is undefined behaviour. The variable ceases to exist when the function returns, so by the time you get to printing, you print garbage values.

If you really want to return an array, you can use an std::array:

typedef std::array<double, 5> DArray5;

DArray5 FillArray() 
{
    DArray5 result; 

    for (size_t i = 0; i < result.size(); ++i){
        result[i] = i;
    }
    return result;
}

Edit This is a C++ only answer. There is no C/C++ language.

like image 171
juanchopanza Avatar answered May 10 '26 10:05

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!