I have the below code which has issue with double return value. How can I fix it?
Code:double *funct( double i )
{
double result = 2.0 * i;
return &result;
}
Printable View
I have the below code which has issue with double return value. How can I fix it?
Code:double *funct( double i )
{
double result = 2.0 * i;
return &result;
}
Don't return a pointer would be one fix.
Make the variable static would be another, but then you couldn't call the function multiple times in the same expression.
Allocate some memory, but then the caller has another problem to deal with.
Why do you even need to return a pointer in this case?
and all the problems of a pointer go away.Code:double funct( double i )
{
double result = 2.0 * i;
return result;
}
It's hard to answer because no-one would write a function to muliply a real value by two. It must be placeholder code.
If you are calculating one value, return it as a "double" (not a double *). If you are calculating several values, but only a small number, then pass in pointers to the values and set them in the function. If you are calculating a long list of values, or if the number of values isn't fixed (e.g. a list of prime factors for an integer), then allocate memory with malloc, fill it with the values, then return it. Usually you will also have to pass in a count varibale via a pointer.