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; }
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; }
Last edited by leo2008; 12-09-2021 at 07:34 AM.
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.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
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; }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
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.
I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
Visit my website for lots of associated C programming resources.
https://github.com/MalcolmMcLean